Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to loop through a 2d array?

I just stumbled upon this blog post about cache algorithms.

The author shows two code samples that loop through a rectangle and compute something (my guess is the computing code is just a placeholder).

On one of the examples, he scans the rectangle vertically, and on the other horizontally. He then says the second is fastest, and that every programmer should know why. Now I must not be a programmer, because to me it looks exactly the same.

Can anyone explain why the former is faster?

like image 654
Alex Turpin Avatar asked Jun 15 '09 17:06

Alex Turpin


People also ask

What type of loop is the most appropriate for iterating a 2D array?

You can loop over a two-dimensional array in Java by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other. Though it's not common to see an array of more than 3 dimensions and 2D arrays is what you will see in most of the places.

Can you use enhanced for loop on 2D array?

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.

How do you print a 2D array for loop?

Code: public class Print2DArrayInJava { public static void main(String[] args) { //below is declaration and intialisation of a 2D array final int[][] matrx = { { 11, 22}, { 41, 52}, }; for (int r = 0; r < matrx. length; r++) { //for loop for row iteration. for (int c = 0; c < matrx[r].

How do you traverse in a 2D array?

The first for loop loops through each row of the 2D array one by one. As the first loop runs through each row, the second (nested) for loop inside the first loop loops through the columns one by one. The nested for loops runs row by row, checking each column within the row before moving on to the next row.


1 Answers

Cache coherence. When you scan horizontally, your data will be closer together in memory, so you will have less cache misses and thus performance will be faster. For a small enough rectangle, this won't matter.

like image 78
Rob Rolnick Avatar answered Sep 20 '22 22:09

Rob Rolnick