Thursday, March 25, 2010

Why Prefix is fast than Postfix

Prefix operation is fast compared to postfix operation.
Lets see how postfix and prefix works.

// postfix
iterator operator++(int)
{
iterator _Tmp = *this;
++*this;
return (_Tmp);
}

// prefix
iterator& operator++()
{
_Ptr = _Acc::_Next(_Ptr);
return (*this);
}

note: one integer dummy variable is used in postfix operation in order to distinguish weather
it is a postfix operation or prefix operation. This dummy variable is never used.
(look at prefix / postfix overloading).
Difference between postfix and prefix:

- One extra object, _Tmp, is necessary in postfix operation
- One extra "copy constructor" is called because of the below line in postfix operation
iterator _Tmp = *this;

Now, lets see two cases

case 1:

for( int i = 0; i < 200; i++)
out[ i ] = in[ i ];
In this case, we do not get the performance even if we are using prefix.
Just one extra integer variable is created and no constructor is called.
case 2:

vector the_vector;
vector::iterator the_iterator;
the_iterator = the_vector.begin();
for( ; the_iterator != the_vector.end(); the_iterator++)
// some operation here
Here, It is sure that we should get the performance if we use prefix instead of postfix.
Just set the iterator to point to the next object in the list.
So, weather it is a integer or a object in a for loop, we should use prefix in order to write the best program.

No comments: