Copying a 2 Dim Array into a 1 dim array

Is there any speedier ways to copy a uniform (i.e. square) two dimesional array into a single dimesional array?

Something faster than:


float[][] source = new float[size][size];
float[] target = new float[size * size];

// .... source is filled 

for(int i = size; i < size; i++) {
    for(int j = size; j < size; j++) {
        target[j*size + i] = source[i][j];
    }
}

As far as I know, that’s the way to do it.

And is that the actual code, or something quickly written for the post? There are a few bugs (loops never entered)…

just wrote something up real quick for the post.

and a System.arraycopy instead of the second loop?
like :
for (int i = 0; i < size; i++)
{
System.arraycopy(source[i], 0, target, i*size, size);
}

as the source and the target have same type

Duh

Mik

Sun would claim arraycopy is faster. I don’t remember the details on that method but it uses some native trickery to boost its speed.

Arraycopy only has to do one bounds check.
The server VM should eliminate the bounds checks and also remove the native call overhead but it’s probably neck and neck. But because almost no-one has the server VM (grrr!) you’ll be better off with the arraycopy method I suspect.

Cas :slight_smile: