Consider the Following Example

 Collection<Integer> coll = new ArrayList<Integer>();

 coll.addAll(Arrays.asList(1,2,3,4,5));

In the above addAll the addition takes place in following steps as Below
1.varargs+autoboxing creates Integer[]
2.Arrays.asList creates a List backed by the array
3.addAll iterates over a Collection using Iterator

Now consider the Below Code

 Collection<Integer> coll = new ArrayList<Integer>();

 coll.addAll(coll, 1,2,3,4,5);

1.varargs+autoboxing creates Integer[]
2.addAll iterates over an array (instead of an Iterable)

We can see now that b) may be faster because:

Arrays.asList call is skipped, i.e. no intermediary List is created.
Since the elements are given in an array, iterating over them may be faster than using Iterator.

Leave a reply