Fastest way to copy one array list to another

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?


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.


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);

链接地址: http://www.djcxy.com/p/17028.html

上一篇: PostgreSQL:使用主键作为排序键非常慢的ORDER BY

下一篇: 将一个数组列表复制到另一个列表的最快方法