while True or while 1

Erik Max Francis max at alcyone.com
Mon Jan 23 14:12:32 EST 2012


Giampaolo Rodolà 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:
	...
> while True: 1.41121292114
> while 1:      1.07101011276
> 
> Most of the times tha't won't make any noticeable difference, but it's
> also true that certain while loops are going to iterate milions of
> times.
> 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".

Such a loop would obviously be I/O-bound, not CPU-bound.  So changing 
the form of the while loop would make minimal difference to its overall 
performance.  It'd be spending the vast majority of its time blocked at 
the OS socket level, not executing the condition of the while loop.

As with most of these things, if one is this worried about performance, 
then either Python was the wrong choice to begin with, or there's a good 
chance that you're worried about something that isn't actually where the 
bottleneck is in the first place.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Jabber erikmaxfrancis
   Think twice before you speak to a friend in need.
    -- Ambrose Bierce



More information about the Python-list mailing list