while true: !!!

Bjorn Pettersen pbjorn at uswest.net
Wed Dec 13 12:31:38 EST 2000


Greg Jorgensen wrote:

> "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:
> [snip]
> 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.

In these cases the compiler doesn't need a temporary variable. If you look at
the (unoptimized) output for your favorite compiler you'll see that they're
identical [I only tested it on msvc, but if it can do it, I'm assuming other
compilers can also <wink> ]

As the previous poster pointed out, it is much more difficult for the compiler
to figure out whether it can optimize something like:

   for (vector<int>::iterator i = v.begin(); i != v.end(); i++)

although msvc gets this "right" also... So the moral is, while it doesn't hurt
to have coding standards saying you should use pre-increment whenever possible,
most people will guess wrong about what the compiler will actually do.

now-back-to-non-infinite-infinite-loops'ly y'rs
-- bjorn





More information about the Python-list mailing list