Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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[][]?

like image 1000
Simon Avatar asked Oct 12 '11 16:10

Simon


People also ask

How do you copy a multidimensional array in Java?

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.

How do you duplicate an object in Java?

The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.


2 Answers

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().

like image 81
dtyler Avatar answered Sep 27 '22 21:09

dtyler


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.

like image 25
Mike Samuel Avatar answered Sep 27 '22 23:09

Mike Samuel