mirror of
https://github.com/Snailclimb/JavaGuide
synced 2025-06-25 02:27:10 +08:00
Update ArrayList-Grow.md
This commit is contained in:
parent
0714db8537
commit
b853a3cd2b
@ -321,14 +321,6 @@ public class EnsureCapacityTest {
|
|||||||
long endTime = System.currentTimeMillis();
|
long endTime = System.currentTimeMillis();
|
||||||
System.out.println("使用ensureCapacity方法前:"+(endTime - startTime));
|
System.out.println("使用ensureCapacity方法前:"+(endTime - startTime));
|
||||||
|
|
||||||
list = new ArrayList<Object>();
|
|
||||||
long startTime1 = System.currentTimeMillis();
|
|
||||||
list.ensureCapacity(N);
|
|
||||||
for (int i = 0; i < N; i++) {
|
|
||||||
list.add(i);
|
|
||||||
}
|
|
||||||
long endTime1 = System.currentTimeMillis();
|
|
||||||
System.out.println("使用ensureCapacity方法后:"+(endTime1 - startTime1));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -336,8 +328,31 @@ public class EnsureCapacityTest {
|
|||||||
运行结果:
|
运行结果:
|
||||||
|
|
||||||
```
|
```
|
||||||
使用ensureCapacity方法前:4637
|
使用ensureCapacity方法前:2158
|
||||||
使用ensureCapacity方法后:241
|
|
||||||
```
|
```
|
||||||
|
|
||||||
通过运行结果,我们可以很明显的看出向 ArrayList 添加大量元素之前最好先使用`ensureCapacity` 方法,以减少增量重新分配的次数
|
```java
|
||||||
|
public class EnsureCapacityTest {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
ArrayList<Object> list = new ArrayList<Object>();
|
||||||
|
final int N = 10000000;
|
||||||
|
list = new ArrayList<Object>();
|
||||||
|
long startTime1 = System.currentTimeMillis();
|
||||||
|
list.ensureCapacity(N);
|
||||||
|
for (int i = 0; i < N; i++) {
|
||||||
|
list.add(i);
|
||||||
|
}
|
||||||
|
long endTime1 = System.currentTimeMillis();
|
||||||
|
System.out.println("使用ensureCapacity方法后:"+(endTime1 - startTime1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
运行结果:
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
使用ensureCapacity方法前:1773
|
||||||
|
```
|
||||||
|
|
||||||
|
通过运行结果,我们可以看出向 ArrayList 添加大量元素之前最好先使用`ensureCapacity` 方法,以减少增量重新分配的次数。
|
||||||
|
Loading…
x
Reference in New Issue
Block a user