I heard people saying prefix increment is faster than postfix
incerement, but I don't know what's the difference. They both are
i = i+1.
i++
++i
Please advise. thanks!!
Consider this program:
void PrintElement(const std::vector<int>::iterator& i)
{
std::cout << *i << " ";
}
int main()
{
std::vector<int> v;
v.push_back(1); v.push_back(2); v.push_back(3);
std::vector<int>::iterator i = v.begin();
while (i != v.end())
PrintElement( i++ );
while (i != v.begin())
PrintElement( --i );
}
Which PrintElement() call is like the more efficient one: the one with
the postincremented parameter (i++) or the pre-decremented (--i)
parameter? Or is there no reason to think that there would be a
difference?
In this case, it is likely that first PrintElement call with the
postfix incremented paramter has more overhead than the second, because
the compiler must increment the iterator i before it calls
PrintElement. But when the call to PrintElement is made, the compiler
must pass the value of i (or a reference to a temporary copy of i) that
i had before it was incremented. Therefore the compiler has little
choice but to make a copy of i before incrementing i, so that it has an
iterator with which it can call PrintElement.
The second PrintElement call applies a prefix operator to the paramter;
the compiler can therefore pass i directly to PrintElement, since its
incremented value is the appropriate value to pass to PrintElement.
Of course, the difference is not likely to be great, but there is
nonetheless a basis for expecting postfix operators to be less
efficient than prefix operators, especially when applied to parameters
in a function call.
Greg