gpt4 book ai didi

java - CollectionUtils.isNotEmpty 和 In Place 检查之间的性能差异

转载 作者:行者123 更新时间:2023-12-02 01:52:46 36 4
gpt4 key购买 nike

最近,当我进行微基准时,我注意到CollectionUtils.isNotEmpty方法消耗了更多时间。我认为可能是我的拼写错误或疏忽。我用集合不为空且大小大于零的就地检查替换了代码。事实证明它要快得多。

我将 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

关于java - CollectionUtils.isNotEmpty 和 In Place 检查之间的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52723826/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com