Speed-up for loops

Stefan Behnel stefan_ml at behnel.de
Fri Sep 3 09:00:13 CEST 2010

Ulrich Eckhardt, 03.09.2010 08:52:
> Tim Wintle wrote:
>> [..] under the hood, cpython does something like this (in psudo-code)
>> itterator = xrange(imax)
>> while 1:
>>    next_attribute = itterator.next
>>    try:
>>      i = next_attribute()
>>    except:
>>      break
>>    a = a + 10
> There is one thing that strikes me here: The code claims that each iteration
> there is a lookup of the 'next' field in the iterator. I would expect that
> this is looked up once before the loop only.
> Can you confirm that or am I misinterpreting your intention here?

It needs to do that. Nothing keeps you from redefining "next" in each call. 
That's even a well known way to implement state machines.

However, as usual, the details are a bit different in CPython, which has a 
C level slot for the "next" method. So the lookup isn't as heavy as it looks.


More information about the Python-list mailing list