最近,当我做 微型基准 时,我注意到 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
答案 0 :(得分:2)
也许加载类或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