[英]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.