Friday, May 11, 2007

Why ++i is faster than i++

Why ++i is faster than i++. Are you ever heard meaning less
discussions like "which is More Fast i++ or  ++ i"? or ++j or j++ or ++k or k++ . hahahaha.  

IF you are serious I can say it will depends upon what is this i and j. If these variables are mere integers it
doesn't matter. We can use both. Both of them are of same speed. Then Problem is with floating point? Or double?.. No noo.. :). Actually there is no problem for ++i or i++.

The problem comes when people do
coding without concentration. Let us look the following example.

class COperator
    int i;

    COperator(){i= 0;}
    operator ++()
     COperator operator ++(int)
        COperator temp = *this;
        return temp;


In an expression as shown in below ,

it; // now i =0
it++; //
now i is 1
pt = it++; //now pt.i = 1 & it.i = 2;

Here for preserving the behaviour of original posix operator(I++), there is a
need for creating the temporary object in the stack((look operator ++(int) ) ,
and we return the temporary object.

So the point is this , some times in loops we often use i++ than ++i. It is a style.
Ok , but is good with integers(etc). But in case of class the obj++ will create
a extra object in stack and there is also a copy operation
. Since in loops
we need is a just an increment (or something like that). That’s why it is
prefered to use ++it rather than I++. If you ever programmed with STL you can
see that STL list uses iterators. They are class objects. So in that iterating
loops use ++it rather than it++. This will save some computing time and memory.

No comments: