What is more efficient, i++ or ++i? [duplicate]
Asked Answered
G

20

15

Exact Duplicate: Is there a performance difference between i++ and ++i in C++?
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 of years, and I would like to get input from the Stack Overflow community.

Gastrocnemius answered 18/2, 2009 at 15:42 Comment(8)
not sure why this has been downvoted soJennefer
See stackoverflow.com/questions/53455 , stackoverflow.com/questions/484462Greyhen
because it's been asked before and nobody felt like finding the original questionGreyhen
Vote for close as exact duplicate. stackoverflow.com/questions/24901 ... stackoverflow.com/questions/53455 ... stackoverflow.com/questions/484462 ... etcSirocco
Multiple duplicate seems pretty obvious reason for downvote. There is a search function both in Google and SO.Arizona
i was not asking the question to make a slow application faster. I was asking because I was curious about how different languages implement them. Sorry for asking a stupid question when I am trying to better understand how things work.Gastrocnemius
Trying to understand something is not stupid, but you should have looked first.Individualize
If this is JavaScript, then there can also bee a speed difference as seen here: jsperf.com/loop-inc-test As of today, i++ would be faster in chrome, and i+= would be faster in IE10. :)Clothespin
A
50

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.

Aggravate answered 18/2, 2009 at 15:46 Comment(4)
On many processors, both of these operations are a single instruction.Kharkov
This Q us tagged with C++ and Java.. I wonder if Java is any different.Bedell
+1 for depending on what i is....for integer primitives, these operation will most likely be the exact same thingOmidyar
@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.Plonk
C
37

I would look elsewhere for optimization potential.

Chimaera answered 18/2, 2009 at 15:45 Comment(0)
M
7

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.

Muslin answered 18/2, 2009 at 15:46 Comment(0)
A
5

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;
Antlia answered 18/2, 2009 at 15:43 Comment(5)
Why the downvote? If you aren't using the side-effect, he's right, there is no difference.Kharkov
I was going to ask the same question.Neophyte
It does not matter today maybe because of cheaper and extremely fast hardware. 10 years ago, however, this question was completely valid.Mamelon
Not all software is intended to run on the latest desktop PCs.Bedell
Then you have a new problem too. Which is faster, "ADD" or "INC"... :-) (hint: it depends on the processor!)Arrestment
C
3

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.

Ceolaceorl answered 18/2, 2009 at 15:45 Comment(0)
N
2

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.

Neophyte answered 18/2, 2009 at 15:44 Comment(1)
that´s right, ++i will first add one and then use the value, i++ will use the value and add one after.Mitran
L
2

++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.

Leighleigha answered 18/2, 2009 at 15:46 Comment(0)
B
2

++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 i = 5; // as an example
int postIncrement(_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...:)

Boatbill answered 18/2, 2009 at 15:49 Comment(0)
L
0

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.

Lyrate answered 18/2, 2009 at 15:44 Comment(0)
L
0

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

Leal answered 18/2, 2009 at 15:45 Comment(2)
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.Arrestment
Perhaps that should be qualified with compiler, compiler version, etc.Terwilliger
F
0

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 I/O, and so on.

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

Fortitude answered 18/2, 2009 at 15:46 Comment(0)
P
0

++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;
Petronia answered 18/2, 2009 at 15:47 Comment(0)
K
0

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.

Kharkov answered 18/2, 2009 at 15:47 Comment(0)
A
0

This Stack Overflow question has a great answer: Is there a performance difference between i++ and ++i in C?

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.

Archetype answered 18/2, 2009 at 15:48 Comment(0)
A
0

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;
Agio answered 18/2, 2009 at 15:49 Comment(0)
S
0

There is no right or wrong answer.

As it depends on:

  1. How it was implemented by the compiler.

  2. What CPU the system runs on.

  3. If i is byte or i is double word

Satinet answered 18/2, 2009 at 15:49 Comment(0)
C
0

It depends upon the context, for example:

x = i++

In this case, 'x' will be equal to 'i', and only after that will 'i' be increased by one.

x = ++i

In this case, 'i' will be increase by one and then the new value of 'x' will be assigned to 'x'.

In the case of a 'for' loop, there is little apparent difference other than performance (++i is faster).

Coonskin answered 18/2, 2009 at 15:50 Comment(0)
G
0

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.

Golightly answered 18/2, 2009 at 15:50 Comment(0)
H
0

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.

Hammett answered 18/2, 2009 at 15:54 Comment(0)
B
-1

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.

Bromism answered 18/2, 2009 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.