while True or while 1

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Dec 13 02:29:56 EST 2010


On Sun, 12 Dec 2010 23:20:40 -0500, Steve Holden wrote:

> On 12/12/2010 2:32 PM, Christian Heimes wrote:
[...]
>> No argue with that! I was merely making a point that "while 1" executes
>> different byte code than "while True". Readability is important but
>> sometimes speed is of the essence. "while 1" is one of the few tricks
>> to speed up tight loops a bit.
> 
> OK, but the figures you quote save you 27.3 ms per million iterations,
> for a grand total saving of 27.3 ns per iteration. So "a bit" is hardly
> worth considering for most programs, is it?


I don't think anyone is saying that people should routinely use "while 1" 
for loops because they're faster than the alternatives. But it is a real, 
if small, optimization for a particular class of tight loops. Using the 
figures shown by Christian, it could be a 20-25% speed up on extremely 
tight loops.

You're right though, it's hardly worth the effort for large, expensive 
loops though -- but then on the other hand, "while 1" is not so 
unreadable that it should be avoided.

I'm actually quite fond of the look of "while 1:", and sometimes use it, 
not because it's faster, but just because I like it.



-- 
Steven



More information about the Python-list mailing list