3

I want to copy a large array of integer values say form array a to array b. I have found a couple of ways to do this, including:

int[] a = new int[]{1,2,3,4,5};
int[] b = new int[5];

System.arraycopy( a, 0, b, 0, a.length );

and

int[] a = new int[]{1,2,3,4,5};
int[] b = (int[])a.clone();

Since this is done on a mobile device i want to be able to do it most efficiently.

Please tell me the best way to do this.

abk
  • 301
  • 2
  • 4
  • 16

5 Answers5

9

System.arraycopy is better way.

Reason: Its implemented through native code so it's more efficient. Josh Bloch suggests (in Effective Java ) to avoid using clone() method to copy/clone an object.

Pls refer this : Effective Java: Analysis of the clone() method

Community
  • 1
  • 1
rai.skumar
  • 10,309
  • 6
  • 39
  • 55
  • 1
    @wojci apples and oranges - this is a comparison between `arraycopy()` and *naive* copying by looping over all the elements - this is not the same thing as `clone()`. – andr Feb 06 '13 at 07:40
2

System.arraycopy( a, 0, b, 0, a.length ); is a nice optimized function, if you build a new object, the execution will be slower..

ƒernando Valle
  • 3,634
  • 6
  • 36
  • 58
2

Yeah, everybody's saying that arraycopy() is better, but most of people tend to forget that Dalvik VM is not Oracle VM and the sources they link to are referring to the Oracle VM. My guess is also that arraycopy() will be faster.

However

If you really, really need for this copy to most optimized, just time both methods and see how they perform. That is always the way to go if you really want to know the real answer. Do that especially on the devices you're targeting since it may be that it behaves drastically different from one device to another.

andr
  • 15,970
  • 10
  • 45
  • 59
2

I think this is the best way to make copies of arrays

int[] b = Arrays.copyOf(a, a.length);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • just be aware that `Arrays.copyOf()` was added later to the API - it's not available in API 8 for example. – andr Feb 06 '13 at 07:44
1

System.arraycopy is native implementation and efficient than cloning. It could copy array in single memorycopy(memcpy).

Find a article on wikipedia - java cloning disadvantage and alternative

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103