Friday, April 6, 2012

Which is faster, '++i' or 'i++' ?

This is a pretty trivial question. I was asked this question in the last interview that I bumped off. The question is always bundled with a for loop..

Which is faster ?

for(i=0;i<n;i++)
for(i=0;i<n;++i)
The correct answer is that both run at same speed. This is because of the optimization done by compilers. So in the end you will get same speed, no matter which of the two you use.

Now, let's think what if the compiler wouldn't optimize ?

In that case, the answer would be the latter one - ++i
This is because when you do i++ you make a copy of the i first and then increment it. But if you do ++i, you just increment it. You don't make a copy. Didn't get it, look below
j=i++
j=++i
In the first case, you make a copy of i which needs to be assigned to j and increment the original i. In the latter case, you just increment the i, because it is the one that needs to be assigned.

No comments:

Post a Comment