Mar*_*lic 3 scala scala-collections scala-2.13
List(1,2,3).sizeIs > 1 // true
List(1,2,3).size > 1 // true
Run Code Online (Sandbox Code Playgroud)
路易斯在评论中提到
...在2.13+上可以使用
sizeIs > 1,它将比size > 1第一个更有效, 因为第一个在返回之前不计算所有大小
向IterableOps#6950添加大小比较方法似乎是引入它的请求请求。
阅读scaladoc
返回一个包含将这些$ coll的大小与测试值进行比较的操作的值类。这些操作是根据
sizeCompare(Int)
我还不清楚为什么sizeIs比常规的效率更高size?
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
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.