22

I was going through increment/decrement operators, and I encountered that if i run a loop in decremental form in that case it will run faster than the same loop in incremental form. I was expecting that both will take equal time since same amount of steps will be followed. I searched through the web but could not find convincing answer to this. Is it due to the case that decrement operator takes less time as compared to increment operator?

for(int i = 100000; i > 0; i--) {}
for(int i = 1; i < 100001; i++) {}
Piyush Bhardwaj
  • 633
  • 6
  • 22

2 Answers2

44

This is because in bytecode comparison with 0 is a different operation than comparison with a non-zero number. Actually i < 10001 requires to first load the number on stack then execute comparison, while i > 0 is executed as one operation. Of course there will be no speed difference in most cases because of JVM optimizations. But we can try to make it visible by running the code with -Xint option (interpreted mode execution only).

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
4

Piyush Bhardwaj

I tested both the loops in online compiler but my increment loop is executing faster then decrement loop.

Program execution depends upon many factors. When sometimes we run the same program on same machine many times we gets different execution times. So it depends upon many factors.

See the results

for(int i = 1; i < 100001; i++) {

}

Increment loop -- http://ideone.com/irdY0e

for(int i = 100000; i > 0; i--) {

}

Decrement loop -- http://ideone.com/yDO9Jf

Sir Evgeniy Dorofeev has given an excellent explanation which an expert only can give.

Finally, you need to consider the performance of your CPU. When considering a benchmark to determine the overall performance of a Java application, bear in mind that bytecode execution, native code execution, and graphics each play a role. Their impact varies depending on the nature of the specific application.

Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126