Reputation: 153
I came across a question related to ArrayList of java in a company written test. My query is just a small part of the actual question.
Lets say we have the following function to copy one ArrayList to another:
void function(List<E> l)
{
List<E> m = new ArrayList<E>(l);
}
The question basically asks to optimize this copy operation. The List may contain a million entries. I have tried the following approaches:
Collections.copy
System.Arraycopy
addAll
But all of these seem to be slower than the given method. I need a method that is faster than the given method or is it the best method that is available?
Upvotes: 10
Views: 7000
Reputation: 3446
If you get dirty, Unsafe will be slightly faster. However you have to get access to the underlying Object array of the ArrayLists using reflection. Use this only if you are in a life-or-death situation regarding performance.
public native void copyMemory(java.lang.Object o, long l, java.lang.Object o1, long l1, long l2);
Upvotes: 0
Reputation: 31724
Well Firstly I think there is a benchmark error. public ArrayList(Collection<? extends E> c)
uses Arrays.copyOf
which internally uses System.arraycopy
(Source here). Hence System.arraycopy
or addAll
cannot be slower than your mentioned code.
For the question, there cannot be a faster way (given you wish to not loose the type information, that might save clock cycles but very trivial) as the operation will have to be O(n)
. And System.arraycopy
is the fastest way out there given it uses native calls to copy them fast.
Upvotes: 5