from: http://stackoverflow.com/a/3343829/5032462html
在stackoverflow上看到的一篇回答,老外真是太professional了,mark一下。最後的summary值得看一下。java
The Java API docs say the following about Collections.addAll
api
The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.app
So if I understand correctly, a) is slower than b):less
a)ide
Collection<Integer> col = new ArrayList<Integer>(); col.addAll(Arrays.asList(1, 2, 3, 4, 5));
b)ui
Collection<Integer> col = new ArrayList<Integer>(); // Collections.addAll(col, Arrays.asList(1, 2, 3, 4, 5)); <-- won't compile Collections.addAll(col, 1, 2, 3, 4, 5);
Let's take a closer look at the two of them:this
// a) col.addAll(Arrays.asList(1, 2, 3, 4, 5));
Here's what happens:spa
Integer[]
Arrays.asList
creates a List<Integer>
backed by the arrayaddAll
iterates over a Collection<Integer>
using Iterator<Integer>
// b) Collections.addAll(col, 1, 2, 3, 4, 5);
Here's what happens:code
Integer[]
addAll
iterates over an array (instead of an Iterable<Integer>
)We can see now that b)
may be faster because:
Arrays.asList
call is skipped, i.e. no intermediary List
is created.Iterator
.That said, unless profiling shows otherwise, the difference isn't likely to be "significant". Do not optimize prematurely. While Java Collection Framework classes may be slower than arrays, they perform more than adequately for most applications.
Collections.addAll(Collection<? super T> c, T... elements)
- varargs i.e. array-basedCollection.addAll(Collection<? extends E> c)
- Collection
-basedCollections.addAll(col, arr)
Collection
, use col.addAll(otherCol)
Collections.addAll(col, otherCol.toArray())