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?
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.
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.
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].
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With