Daniel
Daniel

Reputation: 619

How to copy array with jump?

In my JAVA program, I need to "insert" elements in an array to another array at specific locations with equal interval (4 elements). For example:

byte[] orig = new byte[100000];
byte[] target = new byte[100000*4];
for(int j=0;j<orig.length;j++)
    target[j*4]=orig[j];

The code above works fine but too slow - roughly 50 ms on my laptop. Is there some way that can do the same within a few ms?

Upvotes: 1

Views: 90

Answers (1)

Radiodef
Radiodef

Reputation: 37845

If you reverse the way you are thinking about it by making orig the same size as target but access its indexes with a multiply, you can use System.arraycopy, Arrays.copyOf or clone, any of which might be faster. arraycopy should use a memcpy or something under the hood. copyOf probably calls arraycopy.

So i.e.

byte[] orig = new byte[100000 * 4];

// access index in orig
orig[i * 4] = ...;

byte[] copy = new byte[orig.length];
System.arraycopy(orig, 0, copy, 0, orig.length);

Note this will probably have worse cache performance since the array elements aren't contiguous anymore. (I don't know how much. Better to trust a profiler on that.)

Upvotes: 2

Related Questions