kseehof at neuralintegrator.com
Sun Jun 22 19:01:24 CEST 2003
At 09:08 AM 6/22/2003 Sunday, Bryan wrote:
>in 2.3, what is the best way to write this:
>for i in xrange(100): print 'Hello'
>i used timeit and it seems that repeat is about 10% faster.
>timeit -s"from itertools import repeat" "for i in repeat(None, 100): pass"
>100000 loops, best of 3: 10.4 usec per loop
>timeit "for i in xrange(100): pass"
>100000 loops, best of 3: 11.6 usec per loop
>will xrange be obsoleted? what is the best idiom for repeating a loop n
>times in 2.3 now where you don't care about the index value?
The xrange() function has other uses. For example, xrange() can be used
when you want to loop a large number of iterations, where you -do- care about
the index, without allocating memory for a gigantic array of integers (as would
be the case of range()).
Both idioms seem fine to me. It is extremely unlikely that the performance
difference would ever be meaningful, since you would typically have something
going on inside the loop, so the 10% difference would quickly drop below 1%.
From an artistic point of view it bothers me somewhat (but only a little
0.014%) that there are two equally good ways to express the same thing. Python
is supposed to provide one obvious idiom for each situation. Are we slowing
moving in the direction of Perl?
More information about the Python-list