I read an article in stackoverflow posted 4 years ago, see here: Fastest way to loop through a 2d array? Almost every answer agreed that scan horizontally will faster. I wrote a short Java program to check this, it turned out not the case. I choose 400x400 matrix. The time for scan horizontally is 6 and the time for scan vertically is 3. I checked other sizes of matrix. It also turned out scan vertically is faster. Do I miss something or is it indeed the case?
public class Test {
public static void main(String[] args) {
int row=Integer.parseInt(args[0]);
int column=Integer.parseInt(args[1]);
int[][] bigarray=new int[row][column];
long startTime = System.currentTimeMillis();
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
bigarray[i][j]=Math.abs(i-j)-Math.abs(i-j);
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("scan horizentally time is: ");
System.out.println(totalTime);
int[][] bigarray1=new int[row][column];
long startTime1 = System.currentTimeMillis();
for(int j=0;j<column;j++)
for(int i=0;i<row;i++)
bigarray1[i][j]=Math.abs(i-j)-Math.abs(i-j);
long endTime1 = System.currentTimeMillis();
long totalTime1 = endTime1 - startTime1;
System.out.println("scan vertically time is: ");
System.out.println(totalTime1);
}
}