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++) {}
Increment is always faster than decrement.
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.
Increment operator increases the value of the variable by 1. Decrement operator decreases the value of the variable by 1.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With