Chris
Chris

Reputation: 387

Need of a faster array copy

After doing a bit of reading, I discovered that there are some differences in the ways you can copy arrays in java. For my application I have a recursive tree of nodes, each containing a 2d board array (8x8).

Through profiler testing, the best thing I could come up with is the java.util.Arrays.copyOf(array) method, which uses the native System.arraycopy.

Even with this, I am spending 80% of my time creating new arrays. If anyone has any ideas on how to speed this up I'd appreciate it. Perhaps going to a 64 item array rather than an 8x8 would be faster. I'll test this shortly.

Upvotes: 7

Views: 2947

Answers (5)

Chris
Chris

Reputation: 387

Thanks for the responses. An 8x8 array is essentially 9 array allocations and 1 initialization. With the use of a size 64 array rather than 8x8, the allocation is only once and I can now skip the initialization.

I will, however, look at other ways to improve the speed ... as faster array copies means I can make more nodes :D.

Thanks everyone

Upvotes: 0

R.Moeller
R.Moeller

Reputation: 3446

you need an algorithmic improvement. (are you doing a min max chess algorithm ?)

A possibility is to just copy the reference to each 8x8 array and add a 'shared' flag to each array. Then copy the array only if you actually do change the array. As long you are not changing all of the arrays, this would reduce copying a lot.

Another variant would be to find a more compact representation for your 8x8 array (e.g. some bit magic).

What do your array entries contain ?

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

I've recently done an investigation in this regard (see my answer to my own question at Is there any way to create a primitive array without initialization?, it could have been named "Why Array.copyOf is so slow" or "Why Java is so slow") and even sent an RFE to Oracle. The main idea is that Java spends too much time for useless array initialization. This is about how Arrays.copyOf could have been faster.

Upvotes: 1

rmuller
rmuller

Reputation: 12859

System.arraycopy() is the best if your code needs to be clear.

However, if performance is becomming a real bottleneck, you may look at:

Upvotes: 3

Marko Topolnik
Marko Topolnik

Reputation: 200148

The fact that you are spending 80% time copying arrays means one of two things:

  1. array copying is too slow;
  2. you are barely doing anything else beside copying arrays.

Your copying performance may already be cutting-edge; consider the architecture of your application instead, try reducing the amount of copied data.

Upvotes: 3

Related Questions