亲宝软件园·资讯

展开

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

布道 人气:0

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

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

以下内容是社区里的结论

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
}

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

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的确是更好的选择。

list.size() > 0 && list != null 和 list != null && list.size()>0区别

使用场合

区别

如果list集合还未实例化,可用list != null && list.size() > 0进行判断,

如果用list.size() > 0 && list != null 进行判断的话,会报异常,因为list.size()用 在已经实例化的情况下,但现在未实例化,所以出错;

如果list集合已经实例化,则list != null && list.size() > 0 和 list.size() > 0 && list != null 两者都可以进行判断。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论