while true: !!!
Greg Jorgensen
gregj at pobox.com
Wed Dec 13 02:55:02 EST 2000
"Ben Hutchings" <ben.hutchings at roundpoint.com> wrote in message
news:uhf49kf8r.fsf at roundpoint.com...
> "Greg Jorgensen" <gregj at pobox.com> writes:
> <snip>
> > A flame war broke out a few years ago in comp.lang.c++ over which
> > was better: for ( i=0; i < N; i++ ) or for (i=0; i < N; ++i ). The
> > result is exactly the same, and K&R use the first (postincrement)
> > idiom, but it turns out that ++i is usually a tiny bit more
> > efficient than i++.
> <snip>
>
> For iterators of built-in types (like int) it's unlikely to matter,
> but for iterators of user-defined types the latter may be less
> efficient as it's harder for the compiler to optimise the code for the
> overloaded post-increment operator.
The problem is the temporary variable. The value of i++ is i before the
increment, so the compiler has to save the current value before
incrementing:
int postincrement(int &i)
{
int temp = i;
i = i + 1
return temp;
}
The value of ++i is i after the increment, so no temporary is necessary:
int preincrement(int &i)
{
i = i + 1
return i
}
The difference is negligible in most cases, and modern compilers easily
optimize the temporary out anyway. I was using the flame war over this as an
example of programmers defending a familiar idiom.
--
Greg Jorgensen
Deschooling Society
Portland, Oregon, USA
gregj at pobox.com
More information about the Python-list
mailing list