[英]What is better for the performance CollectionUtils.isEmpty() or collection.isEmpty()
如果您已经知道集合不为null,那么对性能有什么好处。 使用Apache Commons lib中的!collection.isEmpty()
或CollectionUtils.isNotEmpty(collection)
?
或者没有任何性能差异?
CollectionUtils.isNotEmpty的代码(假设我们在这里讨论Apache Commons)...
public static boolean isEmpty(Collection coll)
{
return ((coll == null) || (coll.isEmpty()));
}
public static boolean isNotEmpty(Collection coll)
{
return (!(isEmpty(coll)));
}
...所以,不是真正的区别,一个空检查不会是你的瓶颈;-)
其他答案是正确的,但只是为了确定它:
你为什么要关心? 您的应用程序是否存在性能问题; 并仔细分析指出该方法; 所以你在寻找替代品?
因为......如果不是......那么我们可能会看到PrematureOptimization 。
另一方面:如果“java标准库”提供一个功能; 我总是喜欢他们来自“外部图书馆”的东西。 当然,ApacheCommons现在很公共; 但我只会添加依赖...如果我所有其他代码已经使用它。
差异可以忽略不计(额外的空检查),所有调用都可以通过C1编译器轻松内联。 一般来说,您不应该担心这些简单方法的性能。 即使其中一个慢两倍,它仍然比你的应用程序的其余代码快得多。
Collection.isEmpty作为在apache libs中定义的CollectionUtils间接使用collection.isEmpty()方法。
虽然两者都没有明显的差异,但就是这样
CollectionUtils.isEmpty
是NullSafe
,正如你所说,你知道集合不是空的,所以两者都同样好(几乎)
使用以下程序,您可以在列表中看到1000 Integer的清晰结果。 注意:时间以毫秒为单位
collection.isEmpty几乎是0毫秒
CollectionsUtils.isNotEmpty需要78毫秒
public static void main(String[] args){
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i<1000; i++)
list.add(i);
long startTime = System.currentTimeMillis();
list.isEmpty();
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime);
long startTime2 = System.currentTimeMillis();
CollectionUtils.isNotEmpty(list);
long endTime2 = System.currentTimeMillis();
long totalTime2 = endTime2 - startTime2;
System.out.println(totalTime2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.