Wednesday, May 23, 2012

Which is better Loop or System.arraycopy on modern Java 7?

It's irrelevant.

The compiler will replace your loop with the System.arraycopy anyway.


What was once true in 2007, apparently is largely irrelevant.

Testing array copy vs. for loop with 10 elements...
Copying with System.arraycopy took 33 ms.
Copying with for loop took 45 ms.


Testing array copy vs. for loop with 100 elements...
Copying with System.arraycopy took 8 ms.
Copying with for loop took 16 ms.


Testing array copy vs. for loop with 1000 elements...
Copying with System.arraycopy took 97 ms.
Copying with for loop took 145 ms.


Testing array copy vs. for loop with 10000 elements...
Copying with System.arraycopy took 1583 ms.
Copying with for loop took 1584 ms.

Testing array copy vs. for loop with 100000 elements...
Copying with System.arraycopy took 46101 ms.
Copying with for loop took 47080 ms.

That's right, baby... the compiler replaced the loop with the System.arraycopy natively. And then the Netbeans IDE flagged the loop with a note that it should be replaced with System.arraycopy. You are no longer allowed to do it wrong.

-----

* I ran some more test cases and it turns out you can trigger older loop characteristics for copying variable subsets of the array. If it will loop and copy (at times) less than the full array the loop loses about 20%. And if it's a function set to copy a subset and you use very large numbers it can loose ~50%.

 If you loop with a static final int for small number the loop will compile as an unrolled loop and beat the pants off System.arraycopy.

Looping appears to be much more fickle to optimizations (of which clearly replaced with System.array copy is one.) You likely are better off System.arraycopy in all cases. At least in Windows 7 (Since System.arraycopy is a native function it might differ from one OS to another).

No comments: