In a for loop like for(i=0;i<=10;i ++) and for(i=0;i<=10;+ +i).... i have heard saying that writing ++i in the for loop is faster rather than writing i++.... is that true??... is there any explaination for that???
++i is faster (or) i++ is faster in a for loop???
Collapse
X
-
Tags: None
-
The question is not "++i is faster (or) i++ is faster in a for loop" but "++i is or i++ faster", i.e. being in a for loop is irrelevant to the speed of the operation.
Taking the 2 operators then what they do is
- ++i - increment the value of i and return the new value
- i++ - increment the value of i and return the original value
In 1 having incremented the value of i you can then just use the value of i, however in i++ having incremented the value of i you have to return the original value so you have to deal with 2 values at the same time, the original and new value of i represented by the pseudo code
You can see an extra variable is created and copied to so conceptually ++i is faster.Code:++i { INCREMENT i RETURN i } i++ { result = i INCREMENT i RETURN result }
However we have yet to talk about type because this only really comes into play for classes that have defined operator++() and operator++(int) . In the 2 for loops you give if i is an int (or any other POD type) then the compiler/optimiser is clever enough to see that you don't use the return value at all and optimise away the code that does the copy operation for the i++ implementation. However a classes implementation of the operators is always going to have to do a copy to correctly implement i++.
So the real answer is that ++i is faster than i++ for a class (that supports those operations) but whether it makes a difference to you run time speed is going to be rather dependent on the complexity of the class, e.g. for a simple class holding a single int you will see little difference between ++i and i++ for a complex class a lot of data (or component classes) you might see some difference, especially in a for loop that is repeatedly doing the unrequired copies.
As a matter of course I personally always use ++i in for loops for iterators. -
Code:#include <stdio.h> #include <sys/time.h> int main() { struct timeval start, stop; int i; long long int u1, u2; gettimeofday(&start, NULL); for(i=0;i<=1000000;i++) { } gettimeofday(&stop, NULL); u1 = stop.tv_usec - start.tv_usec; //printf("%lld\n", stop.tv_usec - start.tv_usec); gettimeofday(&start, NULL); for(i=0;i<=1000000;++i) { } gettimeofday(&stop, NULL); u2 = stop.tv_usec - start.tv_usec; //printf("%lld\n", stop.tv_usec - start.tv_usec); //printf("\n"); printf("%lld %lld %lld\n", u1, u2, u1 - u2); }so, b......t ;-)Code:luuk@opensuse:~/tmp> for f in {1..10}; do ./test1; done 4389 4168 221 3769 3775 -6 4357 4390 -33 4408 4386 22 4410 3794 616 3762 3849 -87 4572 4384 188 4412 4386 26 4139 3759 380 3770 4178 -408 luuk@opensuse:~/tmp>Comment
Comment