Java之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:

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

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值