views:

2048

answers:

23

Exact Duplicate: Is there a performance difference between i++ and ++i in C++?
Exact Duplicate: Why should I use ++i?
Exact Duplicate: Difference between i++ and ++i in a loop?


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

I have only used this in Java and C/C++, but I am really asking for all languages that this is implemented in.

In college I had a professor show us that ++i was more efficient but it has been a couple years and I would like to get input from the SO community.

+2  A: 

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;
witkamp
Why the downvote? If you aren't using the side-effect, he's right, there is no difference.
Paul Tomblin
I was going to ask the same question.
Kevin
It does not matter today maybe because of cheaper and extremely fast hardware. 10 years ago, however, this question was completely valid.
Elroy
Not all software is intended to run on the latest desktop PCs.
izb
Then you have a new problem too. Which is faster, "ADD" or "INC"... :-) (hint: it depends on the processor!)
Brian Knoblauch
+1  A: 

Well in C++ I believe they have different uses, depending on when you want the variable updated. Efficiency shouldn't determine when you use one over the other, but I would assume they would have the same efficiency either way.

Kevin
that´s right, ++i will first add one and then use the value, i++ will use the value and add one after.
Decio Lira
A: 

Unless I'm missing something, they should have the same efficiency. They should both result in a single add instruction. It's just a matter of where the add instruction takes place: at the beginning or the end of your line of code.

Steve Rowe
+2  A: 

It does matter! Especially if you're on C++...

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

You should always use the prefix notation to avoid necessary copying overhead and with C++ this matters!

John Leidegren
+21  A: 

I would look elsewhere for optimization potential.

Tor Haugen
A: 

++i takes 1 less processor instruction than i++ in x86 assembly without optimization

Joe Philllips
I'd like to see your reasoning on that. When I reduce it down as a freestanding operation, I get the same number of processor instructions.
Brian Knoblauch
+14  A: 

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.

Edouard A.
On many processors, both of these operations are a single instruction.
Paul Tomblin
It depends on what "i" is.
Edouard A.
This Q us tagged with C++ and Java.. I wonder if Java is any different.
izb
+1 for depending on what i is....for integer primitives, these operation will most likely be the exact same thing
thekidder
@Edourad A: +1 for the clean and simple answer! What about Javascript where there is no compiler? On prototype library they say ++i is faster.
Marco Demajo
+5  A: 

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.

Godeke
A: 

There is no difference. Use the construct that makes the most sense.

If your application runs slowly, I can guarantee you that it will never be because of speed differences in the integer increment operation. If it is, it's a severe bug in the compiler. Speed problems in your application will be algorithmic inefficiencies, waiting for IO, and so on.

Don't worry about problems that you don't have. Premature optimization is the root of all evil.

jrockway
+1  A: 

++i is potentially more efficient for a non-trivial implementation of operator++, but even in that scenario, the compiler may be able to optimize away the intermediate temporary.

Jim Buck
A: 

This explains it a bit.

Learning
A: 

++i is faster because i++ has to store i, then increment it, then return the stored value of i. ++i simply increments i then returns it.

// ++i
i += 1;
return i;

// i++
temp = i;
i += 1;
return temp;
yjerem
A: 

A stand-alone "i++;" or "++i;" should generate equally efficient code. The difference comes if you're using it in an expression, where the "side effect" comes into play.

That said, there was a time, back when "all the world's a Vax", and compilers sucked, that ++i was said to be more efficient that i++, even in a "for (i = 0; i < N; ++i)" type setting.

Paul Tomblin
A: 

This stackoverflow question has a great answer: http://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i

I would like to add that you should use whichever one suits your needs better. Except in the most time critical of applications, it is not important. From an academic perspective too, it is better to write code that expresses what you need and optimize at last.

batbrat
A: 

It's generally easier to type i++, hence it is more efficient in terms of productivity time.

Seriously, though, if i is a native data type (such as int, double, etc) -- no difference.

And it is implementation depended if it's a user-defined type such as

class Type
{
    Type& operator ++(){}
    const Type& operator ++(int i){}
};  

T i;
A: 

There is no right or wrong answer

As it depends on

1) how it was implemented by the complier

2) what Cpu the system runs on

3) If I is byte or I double word

Charles Faiga
+1  A: 

++i doesn't need a temporary variable to store stuff in. Think of them like this:

++i

int preIncrement(int i)
{
    i = i + 1;
    return i;
}

i++

int postIncrement(int i)
{
    int temp = i;
    i = i + 1;
    return temp;
}

See? Postincrement requires a temporary variable. Assuming the compiler doesn't sort it all out for you, which it almost certainly does.

Of course, more important is program logic; you run the risk of encountering The Sad Tragedy of Micro-Optimisation Theatre if you worry about this too much...:)

Robert Grant
A: 

It depends upon the context x=i++ x will have i and i will have i+1 where as x = ++i will have i+1 and i also will have i+1

lakshmanaraj
A: 

In general, it is more efficient to use ++i than i++. The simple reason for this is that ++i is utterly the same as

i += 1;

which for x86 is a single instruction (and likely most other widely used architectures). i++ is however equal to

tmp = i; i += 1;

That is because the old value of 'i' is what i++ evaluates to. And clearly that requires more work than simply i += 1;

But as stated above, this has virtually no impact with a sufficiently clever compiler, as it will optimize unused operations away. For many interpreted languages (example: PHP) there is likely a minimal gain in speed for the ++i; But this increase is negligible.

Zuu
A: 

It's hard to answer this precisely as it depends on the compiler/interpreter implementation.

But generally speaking you can say roughly extend i++ to the following instructions:

COPY i to tmp
INCREMENT tmp
SAVE tmp as i

While ++i will roughly extend to:

LOAD i
INCREMENT i

You can't just say that ++i is faster than i++ since language implementations are pretty smart and they can optimize these instructions when you know that you won't access the temporary value of i++. This usually happens in say a for loop. So in many cases it's just the same.

If you're trying to these kind of micro-optimizations I'd advice you to profile/measure before chosing one over another.

Johan Dahlin
A: 

Generally, in c++, postfix will require the additional construction of the object incremented, while prefix is applied directly to the object. (Or so i've read)

As I am unable to attest to how the compiler handles it due to my limited knowledge on the matter, it could be handled for you making it a moot point.