I was trying to add Integers from 2 sets into single Set via for loop and also using addAll() method provided by Collections. For test purpose, I have populated 2 Sets with
Before you doing anything make sure you've read and understood the discussion here: Java benchmarking - why is the second loop faster?
I would expect addAll to be faster in some situations as it has more information to work with.
For example on an ArrayList addAll can make sure it allocates enough space to add every single element in one step, rather than having to reallocate multiple times if adding large numbers of elements.
It would certainly not be slower as even a naive implementation of it would just do what you do, loop through adding the items.
Concerning your question about how it is handled internally, just check the available source code, e.g. Ctrl-click in eclipse and find the implementation, which in your case is in AbstractCollection
:
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
(from JDK 1.7)
Check the implementation of the addAll method - nothing different that what you'd do - AbstractCollection code