因为性能问题
下面有个简单的例子来证明
“为什么初始化的时候最好设置默认大小”
public static void main(String[] args) {
//得到当前时间
Long nowTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
//默认不设置大小
List<Integer> defaultIntegers = new ArrayList<>();
defaultIntegers.add(1);
}
System.out.println("不设置默认大小,消耗的时间是:" + (System.currentTimeMillis() - nowTime) + "毫秒");
nowTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
//初始化默认大小
List<Integer> initIntegers = new ArrayList<>(1);
initIntegers.add(1);
}
System.out.println("初始化默认大小,消耗的时间是:" + (System.currentTimeMillis() - nowTime) + "毫秒");
}
输出结果
由此可以看出来,设置初始化大小的ArrayList的对象运算会比没有设置ArrayList大小的对象耗时更多,其深层次的原因是若ArrayList对象没有初始化大小时,第一次调用add方法会
额外调用grow方法为该数组对象进行扩容和内存移动
public boolean add(E e) {
modCount++;
add(e, elementData, size);//该方法回调用下面的方法
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();//如果初始化为空数组
elementData[s] = e;
size = s + 1;
}
private Object[] grow() {
return grow(size + 1);
}
/**
* 增加数组的容量,以确保它至少可以容纳minCapacity参数指定的元素数量
*/
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,newCapacity(minCapacity));
}
/**
* 计算需要新增的扩容长度
*/
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity <= 0) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
return Math.max(DEFAULT_CAPACITY, minCapacity);
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)
? newCapacity
: hugeCapacity(minCapacity);
}
版权声明:本文为Jamel_LiToo原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。