deque<long> test_values;
// Fill test_values with 1000000 random numbers
stack<long> test_stack;
clock_t t1 = clock();
deque<long>::iterator j = test_values.begin();
const deque<long>::iterator e = test_values.end();
while(j != e) {
test_stack.push(*j);
++j;
}
clock_t t2 = clock();
Mean (t2-t1) over a couple of runs gives about 13000
But change the prefix op with a post-fix op:
while(j != e) {
test_stack.push(*j++);
}
and the mean shoots up to 18000. /prog/, I ask you this: Why the fuck does it cost so much to store an additional integer?
ಠ_ಠ
Name:
Anonymous2008-11-10 5:41
it's the difference between "increment this value" and "save this value, increment it, and give me the old value". the prefix does the increment immediately, so no temporaries are needed. the postfix has to copy its value, then increment, then pass the previous value to the rest of the expression, so it's got considerably more overhead.
for a more accurate test, move the increment out of the main expression in both cases. however using some optimization flags "should" make the differences nonexistent. in practice however, i've found gcc is sometimes quite stupid with postincrement/decrement operators, so unless you really need the old value anyway, get in the habit of putting the operator first. it's more straightforward anyway.
for some real fun, take a look at the assembly it generates for:
int main(int argc, char **argv) { argc++; return 0; }
and
int main(int argc, char **argv) { ++argc; return 0; }