Reputation: 1965
Which one is faster in Java?
a. for(int i = 100000; i > 0; i--) {}
b. for(int i = 1; i < 100001; i++) {}
Which one is faster in Java?
a. Math.max(a,b);
b. (a>b)?a:b
Upvotes: 0
Views: 721
Reputation: 533870
It is worth remembering that the JVM can compile code which does nothing down to nothing, making the difference about how and when the JVM optimises the code rather than which code is best.
The real question you should be asking yourself is; Why code is clearer to understand? That is what you should use.
Upvotes: 3
Reputation: 10499
Test both two answers and time them. I doubt that there will be any significant difference.
Upvotes: 1
Reputation: 66063
In these cases, it just doesn't matter. All these operations are going to have such negligible running time compared to the VM and GC overhead that you won't save more than a few cycles in total. Even if the difference between the two was, say a 1000 cycles, you're still talking about a difference of 1 microsecond on a 1 GHz processor. It just doesn't matter
Upvotes: 0
Reputation: 23639
Run them both and test them. The difference is going to very small and possibly different on each environment.
Upvotes: 3
Reputation: 56418
When you want to know what is faster, time it.
If you want to know why something is faster, that's different entirely.
Upvotes: 15