如果您已经知道集合不为空,对于性能来说什么更好?是使用
还是两者性能没有区别?
!collection.isEmpty()
还是使用Apache Commons库中的CollectionUtils.isNotEmpty(collection)
?还是两者性能没有区别?
!collection.isEmpty()
还是使用Apache Commons库中的CollectionUtils.isNotEmpty(collection)
?假设我们讨论的是Apache Commons的话,CollectionUtils.isNotEmpty的代码...
public static boolean isEmpty(Collection coll)
{
return ((coll == null) || (coll.isEmpty()));
}
public static boolean isNotEmpty(Collection coll)
{
return (!(isEmpty(coll)));
}
所以,并没有什么区别,那一个空值检查不会成为你的瓶颈 ;-)
差异可以忽略不计(额外的空值检查),所有调用甚至可以被C1编译器轻松内联。一般来说,您不应该担心这些简单方法的性能。即使其中一个方法慢了两倍,它仍然比您应用程序中的其余代码快得多。
Collection.isEmpty作为apache libs中定义的CollectionUtils,间接地将使用collection.isEmpty()方法。
虽然它们两者之间没有明显的区别,只是
CollectionUtils.isEmpty
是NullSafe
的,正如你所说你知道集合不是空的,所以两者都是同样好的(几乎)
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);
}
CollectionUtils
来自哪里? - Konstantin Yovkov!collection.isEmpty()
,虽然我怀疑这不会产生明显的差异。 - Marvin