开发者

What is the fastest way to copy a double[] in Java? [duplicate]

开发者 https://www.devze.com 2023-04-12 08:43 出处:网络
This question already has answers here: .clone() or Arrays.copyOf()? (4 answers) 开发者_运维技巧Closed 9 years ago.
This question already has answers here: .clone() or Arrays.copyOf()? (4 answers) 开发者_运维技巧 Closed 9 years ago.

Simple question, what's the fastest way of copying an array of doubles in Java. I currently do this...

public static double[] clone_doubles(double[] from)
{
    double[] to = new double[from.length];
    for (int i = 0; i < from.length; i++) to[i] = from[i];
    return to;
}

which also does the allocation to avoid overflows, but if there is a quicker way I will separate the allocation from the copy.

I have looked at Arrays.copyOf() and System.arraycopy() but I'm wondering if anyone has any neat tricks.

Edit: How about copying a double[][]?


Java Practices did a comparison of different copy methods on arrays of int:

Here are the results from their site:

java -cp . -Xint ArrayCopier performance 250000

Using clone: 93 ms
Using System.arraycopy: 110 ms
Using Arrays.copyOf: 187 ms
Using for loop: 422 ms

Looks to me like a tie between System.arraycopy() and clone().


System.arraycopy is probably your best bet if you just want to copy from one array to another.

Otherwise

public static double[] clone_doubles(double[] from) {
  return (double[]) from.clone();
}

will give you a clone.


System.arraycopy() is your best bet. Generally, it's implemented with native instructions, probably involving direct calls to the operating system's memory manager.

In Java 6 the performance of arraycopy was improved as "hand-coded assembly stubs are now used for each type size when no overlap occurs".

Read this other post for further details.


Arrays.copy, [].clone and System.arraycopy w/ new object are using the same code path when properly JIT.

Here is the corresponding bug: http://bugs.sun.com/view_bug.do?bug_id=6428387


public static double[] clone_doubles(double[] from)
{
    return Arrays.copyOf(from, from.length);
}

This is internally implemented using System.arrayCopy():

public static double[] copyOf(double[] original, int newLength) {
    double[] copy = new double[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消