0

I did two test about java loop as below. First test with int int w = q[i][j]; the TotalTime is about 5ms. Second test without int w = q[i][j]; The TotalTime is about 40ms. I do not understand that remove one line code, but use much more time. Why?

Test1:

 int[][] p = new int[10000][10000];
        int[][] q = new int[10000][10000];
        long startTime = System.currentTimeMillis();

        for(int i = 0; i<10000; i++){
            for(int j = 0; j<10000; j++){
                int k = p[i][j];
                int w = q[i][j];
            }
        }
        long endTime   = System.currentTimeMillis();
        long TotalTime = endTime - startTime;
        System.out.println(TotalTime); //It is about 5

Test2:

 int[][] p = new int[10000][10000];
    int[][] q = new int[10000][10000];
    long startTime = System.currentTimeMillis();

    for(int i = 0; i<10000; i++){
        for(int j = 0; j<10000; j++){
            int k = p[i][j];
         //   int w = q[i][j];
        }
    }
    long endTime   = System.currentTimeMillis();
    long TotalTime = endTime - startTime;
    System.out.println(TotalTime);  //it is about 40
comlong
  • 59
  • 1
  • 4

1 Answers1

0

I am getting values between 5ms and 9ms for both tests. I suggest running your tests multiple times to get an accurate result and to get rid of outliers. There could be instances where your code might run slower because the CPU might have decided to run some other task, thus halting your code for a few milliseconds. That could be the reason why Test2 took longer to complete.

pvs
  • 54
  • 1
  • 7
  • Thanks for you answer. I use Java 8, it still has such issue. But I change to Java 17, it works well. – comlong Apr 14 '22 at 12:27