1

I understand well how postfix and prefix increments/decrements work. But my question is, in a for loop, which is more efficient or faster, and which is more commonly used and why?

Prefix?

for(i = 0; i < 3; ++i) {...}

Or postfix?

for(i = 0; i < 3; i++) {...}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Neigyl R. Noval
  • 6,018
  • 4
  • 27
  • 45

4 Answers4

1

For ints in this context there is no difference -- the compiler will emit the same code under most optimization levels (I'd venture to say even in the case of no optimization).

In other contexts, like with C++ class instances, there is some difference.

flight
  • 7,162
  • 4
  • 24
  • 31
Foo Bah
  • 25,660
  • 5
  • 55
  • 79
0

Either works, and one is not more efficient or faster than the other in this case. It's common for people to use ++1, maybe because that is what was used in K&R and other influential books.

Gaijinhunter
  • 14,587
  • 4
  • 51
  • 57
  • There is no reason that `++i` (especially in a statement context) needs to create any more "local copies" that `i++` does. –  Sep 25 '11 at 05:51
0

In this particular case, none is actually more efficient than the other. I would expect ++i to be more commonly used, because that's what would be more efficient for other kinds of iterations, like iterator objects.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
0

In my opinion, choosing prefix or postfix in a for loop depends on the language itself. In c++ prefix is more efficient and consistent. Because in the prefix type, compiler does not need to copy of unincremented value. Besides your value must not be an integer, if your value is an object than this prefix type is more powerful.

meandbobbymcgee
  • 341
  • 2
  • 5
  • 12