Skip to content

Commit

Permalink
Update ArrayList-Grow.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Snailclimb committed Dec 29, 2019
1 parent 0714db8 commit b853a3c
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions docs/java/collection/ArrayList-Grow.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,23 +321,38 @@ public class EnsureCapacityTest {
long endTime = System.currentTimeMillis();
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));
}
}
```

运行结果:

```
使用ensureCapacity方法前:4637
使用ensureCapacity方法后:241
使用ensureCapacity方法前:2158
```

```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` 方法,以减少增量重新分配的次数
通过运行结果,我们可以看出向 ArrayList 添加大量元素之前最好先使用`ensureCapacity` 方法,以减少增量重新分配的次数

0 comments on commit b853a3c

Please sign in to comment.