while True or while 1

Ian Kelly ian.g.kelly at gmail.com
Mon Jan 23 12:39:41 EST 2012


On Mon, Jan 23, 2012 at 9:41 AM, Giampaolo Rodolà <g.rodola at gmail.com> wrote:
>
> Il 21 gennaio 2012 22:13, Erik Max Francis <max at alcyone.com> ha scritto:
> > The real reason people still use the `while 1` construct, I would imagine,
> > is just inertia or habit, rather than a conscious, defensive decision.  If
> > it's the latter, it's a case of being _way_ too defensive.
>
> It's also because while 1 is faster:


That's because, as has already been pointed out in the thread, the
compiler is able to store the 1 literal with the code, whereas "True"
requires a name lookup.  If you try the same timing test in Python 3,
you will find that there is no longer any difference.

> Think about receiving a 10 GB file by using a socket. You'd tipically
> have something like this:
>
> while 1:
>    chunk = sock.recv(1024):
>    if not chunk:
>          break
>     ...
>
>
> Now, that's a case where I (personally) want to explicitly use "while
> 1" instead of "while True".


I disagree.  10 GB in 1 KB chunks is going to be 10,000,000 loops,
which as you just demonstrated above, carries an overhead of about 0.4
seconds if we use True instead of 1.  That's entirely trivial compared
to the time needed to actually transfer the file.

Moreover, unless you're doing a significant amount of processing on
the file as you read it, a socket-reading loop like that is likely to
be IO-bound -- which means that after the "while 1" check, the process
is usually going to go to sleep anyway as it waits for more data.  In
that case, the extra 40 nanoseconds for the name lookup makes no
difference at all, as the process wasn't going to do anything useful
with those cycles anyway.

Actually, I have a hard time envisioning a case where the difference
between "while 1" and "while True" in Python 2.x is worth caring
about.  At the point where it might actually start to be noticeable
(say around 100 million iterations), there are surely higher-priority
optimizations to be made, including rewriting parts of the program in
C.

"We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil"
-- Donald Knuth

Cheers,
Ian



More information about the Python-list mailing list