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

- 75,278
- 22
- 140
- 160

- 1,915
- 2
- 19
- 22
-
8homework much?... – Mitch Wheat Jan 11 '11 at 01:29
-
1I would imagine the difference would be negligible and would vary from environment to environment. – Tyler Treat Jan 11 '11 at 01:30
-
5The first two take the same amount of time - 0 - using my java compiler. – President James K. Polk Jan 11 '11 at 01:32
-
5This has been asked a million times before with some good explanations (some, however, are now just historical references). In this case, since it's homework, why not 1) try to answer it yourself 2) justify whatever answer you come up with. – Jan 11 '11 at 01:33
-
since 1.a and 1.b have no side effects, they may be completely elided. 2.a and 2.b may be equivalent if hotspot decides to inline the method call. – Ron Jan 11 '11 at 01:54
6 Answers
When you want to know what is faster, time it.
If you want to know why something is faster, that's different entirely.

- 1
- 1

- 55,313
- 14
- 116
- 115
-
-
1True enough in non-trivial cases, but you have to ask yourself, are you executing these operations often enough that minuscule differences between them add up? Does it matter if one operation is 1 ns faster than another? – Chinmay Kanchi Jan 11 '11 at 01:37
Run them both and test them. The difference is going to very small and possibly different on each environment.

- 23,473
- 9
- 54
- 76
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.

- 525,659
- 79
- 751
- 1,130
Test both two answers and time them. I doubt that there will be any significant difference.

- 10,479
- 4
- 40
- 63
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

- 62,729
- 22
- 87
- 114