【发布时间】:2020-10-03 18:35:00
【问题描述】:
我们发现 ArrayList.addAll(...) 方法不检查给定集合是否为空。 这意味着我们将重新分配内存(将调用 System.arrayCopy(...)),即使我们实际上并不需要它。
我们是否应该为优化添加 IF 检查?
例如:第一个代码的运行时间比第二个代码快 8 倍以上。 看起来我们的优化工作正常,为什么还没有实现呢?
List<Integer> existed = new ArrayList<>();
List<Integer> empty = new ArrayList<>();
for (int i = 0; i < 100_000_000; i++) {
if(!empty.isEmpty())
existed.addAll(empty);
}
VS
List<Integer> existed = new ArrayList<>();
List<Integer> empty = new ArrayList<>();
for (int i = 0; i < 100_000_000; i++) {
existed.addAll(empty);
}
【问题讨论】:
-
“重新分配内存(将调用 System.arrayCopy(...))”是什么意思?
System.arraycopy(…)不分配内存。推荐阅读:How do I write a correct micro-benchmark in Java? -
另外请说明 JDK 版本以及您的测量方式
-
@fps 我们使用 Java 8
标签: java optimization arraylist collections java-8