Speed-up for loops

Hrvoje Niksic hniksic at xemacs.org
Fri Sep 3 13:12:00 CEST 2010

Ulrich Eckhardt <eckhardt at satorlaser.com> writes:

> 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.

It is looked up every time, but the lookup is efficient because "next"
is one of the special methods that have a slot in the C struct that
defines a Python type.  A closer code would be something like:

next_function = iterator->ob_type->tp_next;

...which is as fast as it gets.  CPython implements this in
Python/ceval.c, just look for FOR_ITER.

More information about the Python-list mailing list