while True or while 1

Evan Driscoll edriscoll at wisc.edu
Mon Jan 23 13:05:58 EST 2012


On 01/23/2012 11:39 AM, Ian Kelly wrote:
> "We should forget about small efficiencies, say about 97% of the time:
> premature optimization is the root of all evil"
> -- Donald Knuth

To play devil's advocate for a moment, if you have the choice between 
two ways of writing something, A and B, where both are basically the 
same in terms of difficulty to write, difficulty to maintain, and 
difficulty to understand, but A is faster than B, even if just by a 
hair, why NOT write A?

It's like 'iter++' vs '++iter' in a C++ for loop. For ints, or for some 
iterators with optimization, it makes no difference. But the latter will 
be faster in debug builds, and *might* be faster in release builds if 
you have a complicated iterator. So why NOT make for(...; ...; ++i) the 
typical way of writing a for loop?

In the Python world, is 'while 1' any harder to understand than 'while 
True'? I'm about as staunch a supporter as you'll find for the idea that 
'while 1' should throw an exception, and even *I* think that 'while 1' 
is about the least-offensive idiom out there. If 'while 1' throws you 
off, I'd hate to see what you do when you learn that Python accepts 
loops like 'while x' where the condition evaluates to true if x is a 
non-zero integer and false if x is 0.


All that said, I like the 'while "stuff to do"' idea.

Evan



More information about the Python-list mailing list