Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top