0
  1. Which one is faster in Java?

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

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

  2. Which one is faster in Java?

    a. Math.max(a,b);

    b. (a>b)?a:b

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
Carbonizer
  • 1,915
  • 2
  • 19
  • 22
  • 8
    homework much?... – Mitch Wheat Jan 11 '11 at 01:29
  • 1
    I would imagine the difference would be negligible and would vary from environment to environment. – Tyler Treat Jan 11 '11 at 01:30
  • 5
    The first two take the same amount of time - 0 - using my java compiler. – President James K. Polk Jan 11 '11 at 01:32
  • 5
    This 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 Answers6

15

When you want to know what is faster, time it.

If you want to know why something is faster, that's different entirely.

Community
  • 1
  • 1
Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
  • wiser words are rarely spoken :) – Mihai Toader Jan 11 '11 at 01:32
  • 1
    True 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
3

Run them both and test them. The difference is going to very small and possibly different on each environment.

jzd
  • 23,473
  • 9
  • 54
  • 76
3

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

micro benchmark them using Google Caliper

Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
1

Test both two answers and time them. I doubt that there will be any significant difference.

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
0

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

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114