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[][]
?
A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.
The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With