Home > Blockchain >  Case class: performances of always copying vs check for differences before copying
Case class: performances of always copying vs check for differences before copying

Time:03-10

Lets say i have the following class:

case class Foo(words: List[String])

I want to make a method member of this class that removes an element from the list. I am wondering if there is a notable difference between these two implementations:

def withoutWord(w: String): Foo = copy(words = words.filterNot(_ == w))
def withoutWord(w: String): Foo = {
  if(words contains w) copy(words = words.filterNot(_ == w))
  else this
}

Is it better to check for modifications and return the current instance if nothing has changed or save this time and always copy? In my case, words should rarely exceeds 20 elements and the class has several other fields.

CodePudding user response:

The short answer is "it depends".

Doing the contains check is a win only when it returns false, it is slower than just filtering when you end up filtering after contains. So if you always call withoutWord with a word that's is already there, it's definitely slower and if you never do, it's definitely faster and there's a hit rate at which there's no overall difference.

If the redundant objects and collections are staying around for a while, that will be stressful on the GC (if they're short-lived, most GCs will handle it in such a way that the extra work is infinitesimal) and might lead to performance/stability issues down the road: in that situation, it may be warranted to pay the predictable cost of the contains check every time.

CodePudding user response:

    def withoutWord(w:String):Foo = {
       val selected = words.filterNot(_ == w)
       if(selected.length == words.length) this 
       else copy(words=selected)
    }

This would be more effecient. However, its just a reference copy that we save.

  • Related