Re: Postfix is slower than postfix: how likely?
kanze wrote:
Tom?s wrote:
Seungbeom Kim posted:
Now I wonder: how likely are the cases where you suffer
significant performance loss because you use postfix instead
of prefix? Is there any benchmark that tells postfix can be
measurably slower than prefix?
If we're talking about primitive, built-in types, there's no
difference.
It depends on the compiler. And the machine -- in the C world,
postfix became preferred because on the earliest C compilers for
the PDP-11, it was faster than prefix. For ++; the reverse was
true for --, but since -- was considerably rarer...
If we're talking about user-defined types, then it depends
entirely on the class's definition of the operators.
And the compiler, and the machine.
Since the prefix operator "increments" and the postfix operator
"copies, then increments" a value, it should be clear that the postfix
operator will never be faster than the prefix operator and is much more
likely to be slower.
It's commonly said that the prefix is faster than the postfix,
It's also been pointed out often enough that actual measurements
don't support what is commonly said. That this is more a myth
than anything else.
Unless the compiler can manage to optimize away the extra copy
operation required when postfix-incrementing a value,
prefix-incrementation is certain to be faster.
[...]
This discussion has been done to death.
Never the less, Seungbeom is the first beside myself to post
actual facts, as opposed to speculation. To date, no one has
actually shown a real life iterator where it made a measurable
difference.
The speed difference between prefix and postfix incrementing an
iterator can readily be measured with, say, a std::vector of
std::string's:
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
void Output(std::vector<std::string>::const_iterator iter);
int main()
{
vector<string> v;
v.resize(10000, "abc");
vector<string>::const_iterator iter = v.begin();
do {
Output( ++iter);
} while( iter != v.end());
}
void Output(std::vector<string>::const_iterator iter)
{
std::cout << *iter;
}
The user and system time needed to run this program are:
user 0m0.009s
sys 0m0.007s
Replacing the do loop with this while loop:
while (iter != v.end())
{
Output( iter++);
}
takes measurably more time to complete:
user 0m0.016s
sys 0m0.026s
In other words, due to the extra copying required, the
postfix-incrementing iteration is on the order of 2.5 times as slow as
the same iteration performed with a prefix-incrementing iterator. A
difference in time that should not be at all surprising.
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]