1

I recently started learning java and I am kinda stumped by this---

the below program determines the speed of the for loop--

public class ForLoopExample {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        for(int a = 0; a < 10; a++) {
            System.out.println(a);
        }

        long endTime = System.nanoTime();
        System.out.println("for loop timing =  " + (endTime - startTime) + " ns");
        System.out.println("loop completed");
    }
}

and the output timing is:

for loop timing = 853716 ns

The program determining the speed of the while loop:

public class WhileLoopExample {
    public static void main(String[] args) {
       int a=0;
       long startTime = System.nanoTime();
       while(a < 10) {
            System.out.println(a);
            a++;
       }
       long endTime = System.nanoTime();
       System.out.println("while loop timing = " + (endTime - startTime) + " ns"); 
    }
}

while loop timing=928358 ns

Why does this happen a detailed explanation would be appreciated. 
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
Srirag vu
  • 72
  • 1
  • 7
  • 5
    There shouldnt be a difference. Retry your test with more loop iterations that just 10, that is hardly representative. – f1sh Mar 21 '16 at 10:15
  • 3
    See also http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Andreas Fester Mar 21 '16 at 10:16
  • I don't sure but I think if it doesn't related to JVM background work then in `while` variable `a` can be loaded in register only when it needs. And in `for` loop variable `a` can stored always in register while loop works. Sorry, English isn't my native language. – Denis Sologub Mar 21 '16 at 10:20
  • You're need to see a generated byte code and compare it. – Denis Sologub Mar 21 '16 at 10:21
  • @f1sh I tried what u said and I'm getting an a similar value --------for loop timing= 6410800 ns ---------- while loop timing=7687176 ns – Srirag vu Mar 21 '16 at 10:24
  • And? I wrote already in `while` loop variable `a` can be loaded on each iteration in register – Denis Sologub Mar 21 '16 at 10:26
  • In your case the simplest way is just compare byte code. If it's same in any case then a difference in time due to JVM background work else see comment above. – Denis Sologub Mar 21 '16 at 10:28
  • @ghostman I did that too in the starting but then I received a value suggesting the while loop to be faster :P – Srirag vu Mar 21 '16 at 10:30
  • @Sriragvu 6 ms is way too short for a performance test. Read the duplicate. – assylias Mar 21 '16 at 10:31
  • Then it is happen due to JVM work in background – Denis Sologub Mar 21 '16 at 10:32
  • The main problem is the call to `System.out.println()` - it's buffeted output and it decides when it actually outputs to stdout, which causes a random momentary in-line spike in processing and a corresponding slow down in your code. – Bohemian Mar 21 '16 at 10:33
  • Actually, it is not the most accurate way for java benchmark. There is too many processes going under-the-hood of JVM: code optimization, garbage collection, etc. To get more accurate timing for such a small piece of code you should use micro-benchmark framework like JMH: http://java-performance.info/jmh/ – nukie Mar 21 '16 at 10:34

1 Answers1

3

Rerun your test with more than ten iterations, but also run more iterations of those iterations, say 10000 in the inner loop and ten in the outer and average the results. They should be close.

The reason that there is variance is a result of the operating system and multi threading. The OS is managing many tasks other than your program and those may take a slightly higher priority than your program. This causes sight delays in your execution.

Having a much bigger sample size should decrease the variance in the results.

Nick
  • 766
  • 4
  • 12