See the following snippet:
Long first_begin = System.currentTimeMillis(); // first nested loops for (int i = 0; i < 10; i++) { for (int j = 0; j < 1000000; j++) { // do some stuff } } System.out.println(System.currentTimeMillis() - first_begin); // second nested loops Long seconde_begin = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { for (int j = 0; j < 10; j++) { // do some stuff } } System.out.println(System.currentTimeMillis() - seconde_begin);
I wonder why the first nested loops are slower than the second?
Hello!
Important Note! : I am sorry that I made the variable j starting with 1 by chance, when this question was asked first, I made a correction.
Update: there is no specific logic in the cycle, I just do a test, in fact this is the question asked during the interview, and the interviewer tells me to change the order of the cycles to achieve better performance. By the way, I am using JDK1.5. after some test, I'm more confused because the result of the program is not consistent --- once the first cycle runs faster than the second, but most of the time it runs slower than the second.
nested-loops
didxga
source share