question about xrange performance

Paul McGuire ptmcg at austin.rr.com
Fri Apr 17 15:17:25 EDT 2009


On Apr 17, 1:39 pm, _wolf <wolfgang.l... at gmail.com> wrote:
>
> can it be that a simple diy-class outperforms a python built-in by a
> factor of 180? is there something i have done the wrong way?
> omissions, oversights? do other people get similar figures?
>
> cheers

I wouldn't say you are outperforming xrange until your class also
supports:

for i in xxrange( 10000, 20000 ):
    # do something with i

Wouldn't be difficult, but you're not there yet.

And along the lines with MRAB's comments, xrange is not really
intended for "in" testing, it is there for iteration over a range
without constructing the list of range elements first, which one
notices right away when looping over xrange(1e8) vs. range(1e8).

Your observation is especially useful to keep in mind as Python 3 now
imbues "range" with "xrange" behavior, so if you have code that tests
"blah in range(blee,bloo):", you will get similar poor results.)

And of course, you are cheating a bit with your xxrange "in" test,
since you aren't really verifying that the number is actually in the
given list, you are just testing against the extrema, and relying on
your in-built knowledge that xrange (as you are using it) contains all
the intermediate values.  Compare to testing with xrange(1,100,2) and
you'll find that 10 is *not* in this range, even though 1 <= 10 <
100.  (Extending xxrange to do this as well is also

One might wonder why you are even writing code to test for existence
"in" a range list, when "blee <= blah < bloo" is obviously going to
outperform this kind of code.

-- Paul



More information about the Python-list mailing list