RokL
RokL

Reputation: 2812

For arrays of up to 10 elements: for loop copy or System.arrayCopy?

Assuming a 10 element or less Object[] in Java, what would be the fastest way of copying the array?

  1. for(int i = 0;i < a.length;i++)
    
  2. for(int i = 0,l = a.length;i < l;i++) // i.e. is caching array len in local var faster?
    
  3. System.arrayCopy(a, 0, a2, 0, a.length);
    

Upvotes: 2

Views: 327

Answers (4)

Stephen C
Stephen C

Reputation: 719239

  1. The chances are that the difference between the three alternatives is relatively small.

  2. The chances are that this is irrelevant to your application's overall performance.

  3. The relative difference is likely to depend on the hardware platform and the implementation of Java that you use.

  4. The relative difference will also vary depending on the declared and actual types of the arrays.

You are best off forgetting about this and just coding the way that seems most natural to you. If you find that your completed application is running too slowly, profile it and tune based on the profiling results. At that point it might be worthwhile to try out the three alternatives to see which is faster for your application's specific use-case. (Another approach might be to see if it is sensible to avoid the array copy in the first place.)

Upvotes: 5

mgaert
mgaert

Reputation: 2388

Do get yourself a book on JVM internals (for example, "Oracle JRockit, The Definitive Guide") and realize that what the JVM executes, after warming up, loop unrolling, method inlining, register re-allocation, loop invariant extraction and so on will not even closely resemble what you write in Java source code.

Sorry :-) Otherwise, you will enjoy reading http://www.javaspecialists.eu.

Upvotes: 0

BegemoT
BegemoT

Reputation: 3856

System.arraycopy() is the fastest way to copy array -- as it designed and optimized exactly for this job. There was rumors that for small arrays it hadcoded loop may be faster -- but it is not true for now. System.arraycopy is a JIT intrinsics, and JIT choose best implementation for each case.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691943

Caching the length isn't useful. You're accessing a field directly. And even is it was a method, the JIT would inline and optimize it.

If something had to be optimized, System.arraycopy would contain the optimization.

But the real answer is that it doesn't matter at all. You're not going to obtain a significant gain in performance by choosing the most appropriate way of copying an array of 10 elements or less. If you have a performance problem, then search where it comes from by measuring, and then optimize what must be optimized. For the rest, use what is the most readable and maintainable. What you're doing is premature optimization. And it's the root of all evil (says D. Knuth).

Upvotes: 4

Related Questions