Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pre-increment vs post-increment - for-loop speed [duplicate]

I never saw a tutorial or some lecture, which showed a classic for-loop witout the post-increment-order.

for (int i=0; i<array.length; i++) {}

If you use POST-increment, the variable "i" will be cached, before it will get incremented! But this makes no sense, because the command ends directly.

In my opinion, this makes more sense:

for (int i=0; i<array.length; ++i) {}

If you didn't understand until now, I go a bit further (sry for my english):

In the first loop:

  1. Cache the actual value of i. (note: no move between, so no reason to do this)
  2. Increment i
  3. Go ahead

In the second loop:

  1. Increment i directly
  2. Go ahead.

So the second loop is more performant for no quality loss. Any other opinions?

like image 784
codepleb Avatar asked Aug 23 '13 11:08

codepleb


1 Answers

In Java there is no point in thinking at this level. The Java runtime is so far removed from what you literally write in Java source code that this kind of reasoning loses any meaning. Specifically, the JIT compiler will warp your code to unintelligibility at the machine code level.

like image 189
Marko Topolnik Avatar answered Sep 23 '22 10:09

Marko Topolnik