3

Possible Duplicates:
Loop counter in Java API
Which of these pieces of code is faster in Java?

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

Which one is faster?I read that first for loop is faster.is it true?Then how it become faster than other?please help.

Community
  • 1
  • 1
Raji A C
  • 2,261
  • 4
  • 26
  • 31
  • 7
    How about trying it out? – pcalcao Jun 04 '12 at 11:01
  • This is really interesting :) PHP provides such a result too (most of the time): http://codepad.org/BmxDGE9D – Andrius Naruševičius Jun 04 '12 at 11:06
  • 1
    @MaurícioLinhares - surely you could have found a better Q&A to link to. The accepted answer to the one you linked to is (IMO) plain wrong. – Stephen C Jun 04 '12 at 11:07
  • And yeah, it is clearly a duplicate as stated by Maurício Linhares. – Andrius Naruševičius Jun 04 '12 at 11:07
  • Both can be optimized away since nothing happens in the loop. As soon as something happens there, the time spend just for for looping becomes negligible. – user unknown Jun 04 '12 at 11:09
  • 1
    See this one for a better answer - http://stackoverflow.com/questions/1656506/which-of-these-pieces-of-code-is-faster-in-java – Stephen C Jun 04 '12 at 11:10
  • @StephenC Edited the question with this better link. – assylias Jun 04 '12 at 11:13
  • @AndriusNaruševičius - because it makes the mistake of thinking that you can infer the speed of code from looking at the bytecodes. In fact, the JIT compiler is quite likely to produce native code that is sufficiently different that bytecode-based reasoning cannot be trusted. – Stephen C Jun 04 '12 at 11:16

1 Answers1

0

There is no way to tell which of the two is faster.

If all you provide is a snippet of Java code, all we have to go on is the Java Language Specification. Since the Java Language Specification never mentions any timing aspects there's no way to answer the question.

It is similar to asking your math teacher, "Which is faster to compute, 17+17 or 17*17?" Your math teacher will just stare at you and at best respond with something like, "are you using pen and paper or a pocket calculator?"

aioobe
  • 413,195
  • 112
  • 811
  • 826