Java之size()>0 和isEmpt()性能考量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/itsoftchenfei/article/details/82885461

为何要写这篇呢?主要是要纠正一个长期以来的误区:size()>0 一定比isEmpt()性能差。

以下内容是社区里的结论:

方法一(数据量大,效率低): if(list!=null && list.size()>0){
}

方法二(数据量大,效率高): if(list!=null && !list.isEmpty()){
}

sonar的规范是这样描述:Collection.isEmpty() should be used to test for emptiness

Using Collection.size() to test for emptiness works, but using Collection.isEmpty() makes the code more readable and can be more performant. The time complexity of any isEmpty() method implementation should be O(1) whereas some implementations of size() can be O(n).

明白了吧!

主要是语义更明确,其实判断List、Map、Set是否为空及效率比较真的没有多大的必要,确实是没有大多的提升。看源码:

ArrayList:

public int size() {
    return size;
}
public boolean isEmpty() {
    return size == 0;
}


HashSet:

public int size() {
    return map.size();
}
public boolean isEmpty() {
    return map.isEmpty();
}


ConcurrentHashMap:
 

public int size() {
    long n = sumCount();
    return ((n < 0L) ? 0 :
            (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE :
            (int)n);
}
public boolean isEmpty() {
    return sumCount() <= 0L; // ignore transient negative values
}

其次,有些时候确实它更快,如果你使用了ConcurrentLinkedQueueNavigableMapNavigableSet,看源码:

ConcurrentSkipListMap

public int size() {
    long count = 0;
    for (Node<K,V> n = findFirst(); n != null; n = n.next) {
        if (n.getValidValue() != null)
            ++count;
    }
    return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count;
}
public boolean isEmpty() {
    return findFirst() == null;
}

最后,计算机是门需要刨根问底(点进源码看看)的技术活,不能人云亦云。综上所述,isEmpt的确是更好的选择。

猜你喜欢

转载自blog.csdn.net/itsoftchenfei/article/details/82885461