sum2000
sum2000

Reputation: 1393

Confusion on loops in java

Which one is faster in java ?

a)  for(int i = 100000; i > 0; i--) {}
b)  for(int i = 1; i < 100001; i++) {}

I have been looking for explanation to the answer which is option a, anyone? any help is appreciated

Upvotes: 0

Views: 196

Answers (4)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235984

There are situations when a reverse loop might be slightly faster in Java. Here's a benchmark showing an example. Typically, the difference is explained by implementation details in the increment/decrement instructions or in the loop-termination comparison instructions, both in the context of the underlying processor architecture. In more complex examples, reversing the loop can help eliminate dependencies and thus enable other optimizations, or can improve memory locality and caching, even garbage collection behavior.

One can not assume that either kind of loop will always be faster, for all cases - a benchmark would be needed to determine which one performs better on a given platform, for a concrete case. And I'm not even considering what the JIT compiler has to do with this.

Anyway, this is the sort of micro-optimizations that can make code more difficult to read, without providing a noticeable performance boost. And so it's better to avoid them unless strictly necessary, remember - "premature optimization is the root of all evil".

Upvotes: 7

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147144

Generally, Oracle HotSpot has an emphasis on optimisation in real code, which means that forward loop optimisations are more likely to be implemented than backward loops. From a machine code point of view, the decrementing loop may save an instruction, but it is unlikely to have a significant impact on performance, particularly when there is much memory access going on. I understand modern CPUs are more or less as happy going backwards as forwards (historically there was a time when they were better optimised for forward access). They'll even optimise certain stride access patterns.

(Also HotSpot (at least the Server/C2 flavour) is capable of removing empty loops.)

Upvotes: 1

Simone-Cu
Simone-Cu

Reputation: 1129

You told that the answer is a so, I guess an answer: java virtual machine will "translate" the comparison with zero in a faster way.

Upvotes: 0

phatfingers
phatfingers

Reputation: 10250

Just talking out of my hat, but I know assembly languages have specific comparisons to zero that take fewer cycles than comparisons between registered values.

Upvotes: 2

Related Questions