score:5

Accepted answer

as far as i understand the changes.

the idea is that for collections that do not have a o(1) (constant) size. then, sizeis can be more efficient, specially for comparisons with small values (like 1 in the comment).

but why?
simple, because instead of computing all the size and then doing the comparison, sizeis returns an object which when computing the comparison, can return early.
for example, lets check the code

def sizecompare(othersize: int): int = {
  if (othersize < 0) 1
  else {
    val known = knownsize
    if (known >= 0) integer.compare(known, othersize)
    else {
      var i = 0
      val it = iterator
      while (it.hasnext) {
        if (i == othersize) return if (it.hasnext) 1 else 0 // here!!! - return as fast as possible.
        it.next()
        i += 1
      }
      i - othersize
    }
  }
}

thus, in the example of the comment, suppose a very very very long list of three elements. sizeis > 1 will return as soon as it knows that the list has at least one element and hasmore. thus, saving the cost of traversing the other two elements to compute a size of 3 and then doing the comparison.

note that: if the size of the collection is greater than the comparing value, then the performance would be roughly the same (maybe slower than just size due the extra comparisons on each cycle). thus, i would only recommend this for comparisons with small values, or when you believe the values will be smaller than the collection.


Related Query

More Query from same tag