- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is there a performance difference between i++ and ++i in C++ program?
The effective result of i++ and ++i are same. The only difference is that the i++ increases the value of i after assigning it, and for ++i, it increases the value first, then assigns its value. We can see the difference in the following code.
Example Code
#include<iostream> using namespace std; int main() { int x = 3, y, z; y = x++; z = ++x; cout << x << ", " << y << ", " << z; return 0; }
Output
5, 3, 5
Now, the question comes, that as they are doing the same task but in different order, then is there any performance issue or both are same?
Well, the performance of these operations highly dependent on the underlying architecture. One is incrementing value that is stored in the memory, it means the Von-Neumann bottleneck is basically the limiting factor in both cases.
Though we can say that the ++i is slightly faster than i++. The i++ takes local copy of the value of i before incrementing, while ++i never does. Sometimes some compiler optimizes the code if possible. But that optimization is not always being effective, or not all compiler does this thing.