Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does decrement loop runs faster than increment loop? [duplicate]

Tags:

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++) {} 
like image 882
Piyush Bhardwaj Avatar asked May 10 '13 06:05

Piyush Bhardwaj


People also ask

Which is faster increment or decrement?

Increment is always faster than decrement.

What is the difference between decrement and increment?

The increment operator increases, and the decrement operator decreases, the value of its operand by 1. The operand must have an arithmetic or pointer data type, and must refer to a modifiable data object.

What will happen if you use increment and decrement operators on constant?

Increment operator increases the value of the variable by 1. Decrement operator decreases the value of the variable by 1.


1 Answers

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).

like image 106
Evgeniy Dorofeev Avatar answered Sep 21 '22 15:09

Evgeniy Dorofeev