The function ArrayList.add()
works very fast. I checked the source code, and saw the implement was Arrays.copyOf()
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
But when I use the method Arrays.copyOf()
in my code, it becomes very slow. You can just run the code below to see it:
public class TestArrayCopy {
public static void main(String[] args) {
long t = System.currentTimeMillis();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
list.add(i, i);
}
System.out.println(System.currentTimeMillis() - t);
t = System.currentTimeMillis();
Integer[] array = new Integer[0];
for (int i = 0; i < 100000; i++) {
array = Arrays.copyOf(array, array.length +1);
array[i] = i;
}
System.out.println(System.currentTimeMillis() - t);
}
}
Any ideas?