Why is ++i faster than i++ in C++? (2024)

Why is ++i faster than i++ in C++? (1)

I’ve heard this question come up a few times in C++ programming circles, “Why is ++i faster/better than i++?”

The short answer is: i++ has to make a copy of the object and ++i does not. The long answer involves some code examples.

int i = 1; int j = i++; // j is equal to 1, because i is incremented after the value is returned, // which means a copy was made of the old value 
int k = ++i; // k is equal to 3, because i is incremented, then returned. No copy is needed

Or a more robust example of the operator overloads:

class integer { public: integer(int t_value) : m_value(t_value) { } int get_value() { return m_value; } integer &operator++() // pre increment operator  { ++m_value; return *this; } integer operator++(int) // post increment operator  { integer old = *this; // a copy is made, it's cheap, but it's still a copy  ++m_value; return old; // Return old copy  } private: int m_value;};

You might ask, “why cannot the C++ compiler optimize away the copy of you don’t use it?”

Really:

int i=1; ++i; //why is this i++; //faster than this if I'm not using the copied returned value?

It’s possible that the compiler may optimize away the copy for you, but it’s also possible that your post-increment operator overload has other side effects that the compiler cannot optimize for without changing the meaning of your code. On a side note, it’s rare that you literally want to increment and return the old value, so ++i is often more semantically correct than i++, besides being more efficient.

Why is ++i faster than i++ in C++? (2024)

FAQs

Is ++ I faster than I ++ C++? ›

Is ++ I faster than I ++ C++?

Why is ++ I faster than I 1? ›

Why is ++ I faster than I 1?

Is ++ I in loop faster than I ++? ›

Is ++ I in loop faster than I ++?

Top Articles
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 6051

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.