The Java API docs say the following about Collections.addAll
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.
So if I understand correctly, a) is slower than b):
a)
Collection<Integer> col = new ArrayList<Integer>();
col.addAll(Arrays.asList(1, 2, 3, 4, 5));
b)
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);
Can anyone explain to me, why that is?
edited:
corrected code example. thx to polygenelubricants
Let’s take a closer look at the two of them:
Here’s what happens:
Integer[]Arrays.asListcreates aList<Integer>backed by the arrayaddAlliterates over aCollection<Integer>usingIterator<Integer>Here’s what happens:
Integer[]addAlliterates over an array (instead of anIterable<Integer>)We can see now that
b)may be faster because:Arrays.asListcall is skipped, i.e. no intermediaryListis 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.
API links
Collections.addAll(Collection<? super T> c, T... elements)– varargs i.e. array-basedCollection.addAll(Collection<? extends E> c)–Collection-basedSee also
Related questions
Summary
Collections.addAll(col, arr)Collection, usecol.addAll(otherCol)Collections.addAll(col, otherCol.toArray())