服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java中关于size()>0 和isEmpt()的性能考量

Java中关于size()>0 和isEmpt()的性能考量

2022-08-07 13:50布道 Java教程

这篇文章主要介绍了Java中关于size()>0 和isEmpt()性能考量,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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

为何要写这篇呢?主要是要纠正一个长期以来的误区: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:

?
1
2
3
4
5
6
public int size() {
    return size;
}
public boolean isEmpty() {
    return size == 0;
}

HashSet:

?
1
2
3
4
5
6
public int size() {
    return map.size();
}
public boolean isEmpty() {
    return map.isEmpty();
}

ConcurrentHashMap:

?
1
2
3
4
5
6
7
8
9
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

?
1
2
3
4
5
6
7
8
9
10
11
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==null; 此时list还没有实例化(new);
  • list.size()==0; 此时表明list已经实例化了,但list集合里面没有元素,长度为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 两者都可以进行判断。

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

原文链接:https://blog.csdn.net/alex_xfboy/article/details/82885461

延伸 · 阅读

精彩推荐