Carbonizer
Carbonizer

Reputation: 1965

Which is faster in java

  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

Upvotes: 0

Views: 721

Answers (6)

Peter Lawrey
Peter Lawrey

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

Kevin Ji
Kevin Ji

Reputation: 10499

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

Upvotes: 1

Chinmay Kanchi
Chinmay Kanchi

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

Aravind Yarram
Aravind Yarram

Reputation: 80192

micro benchmark them using Google Caliper

Upvotes: 2

jzd
jzd

Reputation: 23639

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

Upvotes: 3

Daniel DiPaolo
Daniel DiPaolo

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

Related Questions