java - CollectionUtils.isNotEmpty 和就地检查之间的性能差异
问题描述
最近在做微基准测试时,我注意到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
推荐阅读
- assembly - 无法让 .define 与 sdasz80(sdcc 汇编器)一起使用
- c# - 如何更改 CalendarDatePicker UWP 的语言?
- php - 使用其他字段 PHP 更新外键
- java - 将 XML 解析为 base64 和 json
- java - 在客户端调用 onOpen() 之前调用 websocket ServerEndpoint
- python - 检查目标时出错:预期 dense_3 的形状为 (1,) 但得到的数组的形状为 (86,)
- push-notification - 自定义模板通知在 Xamarin.iOS 项目中不起作用
- macos - Docker 启动 MacOS 需要很长时间
- java - 使用 gradle 的多个 IntellijIdea 版本的插件
- javascript - 具有相同变量的 2 个不同属性的条形图 [Chart.Js]