What is more efficient, i++ or ++i?

22,311

Solution 1

i++ :

  • create a temporary copy of i
  • increment i
  • return the temporary copy

++i :

  • increment i
  • return i

With optimizations on, it is quite possible that the resulting assembly is identical, however ++i is more efficient.

edit : keep in mind that in C++, i may be whatever object that support the prefix and postfix ++ operator. For complex objects, the temporary copy cost is non negligible.

Solution 2

I would look elsewhere for optimization potential.

Solution 3

Efficiency shouldn't be your concern: it is meaning. The two are not the same, unless they are freestanding: one operates pre-use of the value, the other post.

int i; i = 1; cout << i++; //Returns 1

int i; i = 1; cout << ++i; //Returns 2

When meaning isn't important, most compilers will translate both ++i and i++ (say in a for loop) into the same machine/VM code.

Solution 4

It does not matter on a modern compiler.

int v = i++;  

is the same as

int v = i;
i = i + 1;

A modern compiler will discover that v is unused and the code to calculate v is pure (no side effects). Then it will remove v and the assignment code and will generate this

i = i + 1;

Solution 5

It does matter! Especially if you're in C++ land with custom iterator protocols...

++i // the prefered way, unless..
auto j = i++ // this is what you need

You should use the prefix notation to avoid a necessary copying overhead but it only applies to iterators, it doesn't apply to builtin native types, those are just one instruction regardless.

Share:
22,311
trench
Author by

trench

Simple programmer trying to grow.

Updated on August 12, 2020

Comments