Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient System.arraycopy on multidimensional arrays

Tags:

java

arrays

I'm aware that a common performance refactoring is to replace simple for's by System.arraycopy.

I want to ask about:

  1. When exactly does system.arraycopy begin to make sense (considering it's a native method call). Does copying small things say, < 32 have any advantage?

  2. Is it my impression, or is it not simply possible to copy (efficiently) a cycle like this with arraycopy:

       for (int j = 0; j < 2; ++j) {
           vpr[m][s + j][i] = vr[j];
       }
    
like image 478
i30817 Avatar asked Jan 14 '10 23:01

i30817


2 Answers

It's not difficult to use System.arraycopy to do a quick deep copy. Here's an example for a 2D array:

for (int i = 0; i < src.length; i++) {
    System.arraycopy(src[i], 0, dest[i], 0, src[0].length);
}

From a quick timing test, using this to copy a 1000x1000 2D array 100 times takes 40 milliseconds, versus 1740 milliseconds using the more obvious two for loops and assignment.

like image 182
adammtlx Avatar answered Oct 03 '22 19:10

adammtlx


AFAIK, System.arrayCopy is the most efficient and best way to copy your arrays. I am not aware of any situations where the alternate way of implementing your own loops would be much more efficient for direct copies.

like image 20
Sands Avatar answered Oct 03 '22 20:10

Sands