我对java.util.ArrayList#add()
方法的性能有些担心(对我来说似乎太慢了),所以我下载了 Java 源代码并查看了ArrayList
实现(看起来不错),我复制了方法clear()
并add()
创建了自己的 ArrayList2:
public class ArrayList2<E>
{
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] EMPTY_ELEMENTDATA = {};
static int MAX_ARRAY_SIZE = 50000;
private transient Object[] elementData;
private int size;
public ArrayList2(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0)
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
if (minCapacity - elementData.length > 0){
//System.out.println("WHAT"); //when this line is uncommented performance is improved
grow(minCapacity);
}
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
public void clear() {
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
}
这当然与java.util.ArrayList
. 未注释第 49 行时会发生奇怪的事情。它包含这个:
System.out.println("What");
在此更改之后,add 方法的运行速度提高了 3-4 倍,这很奇怪,因为该行位于一个从未执行过的代码块中,因此应该不会影响性能。我使用了一个简单的测试来测量不同方法所花费的时间。这是输出:
**************************************
Filling Array List 2 took : 2107
Emptying Array List 2 took : 149
**************************************
**************************************
Filling Array List 3 took : 565
Emptying Array List 3 took : 182
**************************************
这种逻辑上不相关的变化如何能如此显着地提高性能?有人可以解释一下吗?这对我来说真的没有任何意义,目前在我看来是 java.util.ArrayList 中的一个大性能问题。
你可以在这里下载源代码:
您可以使用以下 maven 命令运行它:
mvn exec:java -Dexec.mainClass="Test"