tgkprog tgkprog - 4 months ago 9
Java Question

Java arrays speed : copy & re use or create new

For an algorithm need a copy of a an array. Have an original and a temp. Need to process "turns" so can re use the temp, but need to start from that state.

After each turn, done with the temp (but need it again for next iteration). Is it better to copy the temp to the original or just assign the original to the temp and make a new array for the temp? Size will be 5x5 to 300x300 2D int array.

//int [][]orig //initialized elsewhere
int [][]newData = new int[orig.length][orig[0].length];
for (int i = 0; i < turns; i++) {
proc1Turn(orig, newData);
//after 1 turn copy newData to orig OR assign to orig
//and create new array for newData?
}


Which will be faster or another way? Will that be pretty much the same (for any system) if we have enough RAM/ free heap for the JVM?

Answer

Is it better to copy the temp to the original or just assign the original to the temp and make a new array for the temp?

It is better to do neither. Just swap the array references.

int [][] t = newdata;
newdata = orig;
orig = newdata;

This avoids allocating a new array (which needs to be cleared by the runtime, and which requires that the previous array be garbage collected at some point).

Comments