Wednesday, May 18, 2011

Iterating over 2 Dimensional Arrays

Iterating down rows, then across columns is often better. The most common practice is for the outer loop be for the row and the inner loop for the column. If your program requires the outer iteration by columns, that's fine, but the default row-first iteration gives the best performance because "locality of reference" improves the perfomance of cache and virtual memory. It also allows use of the handy foreach loop.

int[][] a2 = new int[ROWS][COLS];

String output = ""; // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
output += " " + a2[row][col];
}
output += "\n";
}


foreach style for loop


for (int[] row : a2) {
for (int val : row) {
output += " " + val;
}
output += "\n";
}

No comments:

Post a Comment

Chitika