Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance difference between i++ and ++i in C?

Is there a performance difference between i++ and ++i if the resulting value is not used?

like image 497
Mark Harrison Avatar asked Aug 24 '08 06:08

Mark Harrison


People also ask

What is faster i ++ or ++ i?

++i is sometimes faster than, and is never slower than, i++. For intrinsic types like int, it doesn't matter: ++i and i++ are the same speed. For class types like iterators or the previous FAQ's Number class, ++i very well might be faster than i++ since the latter might make a copy of the this object.

Is ++ i or i ++ more efficient?

According to the Google C++ Style Guide, "when the return value is ignored, the 'pre' form ( ++i ) is never less efficient than the 'post' form ( i++ ), and is often more efficient."

What is the difference between -- I and I --?

There is no difference in your case. --i is pre-decrement and i-- is post-decrement.

What is faster ++ i or i ++ where i is an integer variable?

In C++ the faster is ++i; due to its object. However some compilers may optimize the post-increment operator.


1 Answers

Executive summary: No.

i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away.

We can demonstrate this by looking at the code for this function, both with ++i and i++.

$ cat i++.c extern void g(int i); void f() {     int i;      for (i = 0; i < 100; i++)         g(i);  } 

The files are the same, except for ++i and i++:

$ diff i++.c ++i.c 6c6 <     for (i = 0; i < 100; i++) --- >     for (i = 0; i < 100; ++i) 

We'll compile them, and also get the generated assembler:

$ gcc -c i++.c ++i.c $ gcc -S i++.c ++i.c 

And we can see that both the generated object and assembler files are the same.

$ md5 i++.s ++i.s MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e  $ md5 *.o MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22 MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22 
like image 196
Mark Harrison Avatar answered Sep 21 '22 19:09

Mark Harrison