![](/img/trans.png)
[英]Is CollectionUtils.isNotEmpty() better than a null check?
[英]Performance difference between CollectionUtils.isNotEmpty and In Place check
最近,在進行微基准測試時 ,我注意到CollectionUtils.isNotEmpty方法消耗了更多時間。 我以為我可能有錯別字或疏忽大意。 我將代碼替換為就位檢查集合不為null且大小大於零。 事實證明它要快得多。
我將方法CollectionUtils.isNotEmpty的源代碼放入了我的代碼中,它也更快。
是什么原因導致這種差異?
注意:我知道微基准測試不會對JVM優化的整個領域有所幫助。 我專門在循環中放置了100次,如果它超過了JVM對其進行優化的次數。 在Windows和Linux中檢查的代碼與性能差異相似。
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
public class TestCollectionUtilsPerf {
public static void main(String[] args) {
List<String> stringList = Arrays
.asList(new String[] { "StringOne", "StringTwo", "StringThree", "StringFour", "StringFive" });
long startTime = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (stringList != null && stringList.size() != 0) {
continue;
}
}
System.out.format("Manual Inplace Check Time taken is : %d µs %n", (System.nanoTime() - startTime) / 1000);
startTime = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (CollectionUtils.isNotEmpty(stringList)) {
continue;
}
}
System.out.format("Collection Utils Time taken is : %d µs %n", (System.nanoTime() - startTime) / 1000);
startTime = System.nanoTime();
for (int i = 0; i < 100; i++) {
if (isNotEmpty(stringList)) {
continue;
}
}
System.out.format("Manual Method Check Time taken is : %d µs %n", (System.nanoTime() - startTime) / 1000);
}
public static boolean isEmpty(final Collection<?> coll) {
return coll == null || coll.isEmpty();
}
public static boolean isNotEmpty(final Collection<?> coll) {
return !isEmpty(coll);
}
}
輸出:
手動就位檢查所需的時間為:61 µs
收集實用程序花費的時間是:237193 µs
手動方法檢查時間為:66 µs
也許加載類或jar包花費了很多時間,您可以在開始時嘗試調用CollectionUtils.isEmpty
。
public static void main(String[] args) {
List<String> stringList = Arrays
.asList(new String[] { "StringOne", "StringTwo", "StringThree", "StringFour", "StringFive" });
//try it at the begging to load the class
CollectionUtils.isEmpty(stringList);
......
}
和我的出路
Manual Inplace Check Time taken is : 10 µs
Collection Utils Time taken is : 21 µs
Manual Method Check Time taken is : 25 µs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.