The fastest way to copy one list of arrays to another

I came across a question related to ArrayList from java in a written test of a company. My request is just a small part of the actual question.

Suppose 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 is mainly aimed at optimizing this copy operation. A list can contain a million entries. I tried the following approaches:

Collections.copy

System.arraycopy

addAll

But they all seem slower than this method. Do I need a method that is faster than this method, or is it the best method that is available?

+7
java arraylist
source share
2 answers

Well, firstly, I think there is a reference error. public ArrayList(Collection<? extends E> c) uses Arrays.copyOf , which internally uses System.arraycopy (Source here ). Therefore, System.arraycopy or addAll cannot be slower than your code mentioned.

There cannot be a faster way in this question (if you want not to lose type information that could save hours, but very trivial), since the operation should be O(n) . And System.arraycopy is the fastest way when it uses its own calls to quickly copy.

+3
source share

If you get dirty, Unsafe will be a little faster. However, you must access the underlying array of objects in the ArrayLists array 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);

0
source share

All Articles