while True or while 1

Giampaolo Rodolà g.rodola at gmail.com
Mon Jan 23 15:20:23 EST 2012


Il 23 gennaio 2012 20:12, Erik Max Francis <max at alcyone.com> ha scritto:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list

Obviously, you're right. I picked up the wrong example.
My point is 1.41121292114 vs 1.07101011276 *might* make some
difference in certain cases.
I just can't come up with a good example where that would be justified. =)


--- Giampaolo
http://code.google.com/p/pyftpdlib/
http://code.google.com/p/psutil/
http://code.google.com/p/pysendfile/



More information about the Python-list mailing list