range() vs xrange() Python2|3 issues for performance
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Tue Aug 2 05:26:45 EDT 2011
Am 02.08.2011 09:12 schrieb harrismh777:
> The following is intended as a helpful small extension to the xrange()
> range() discussion brought up this past weekend by Billy Mays...
>
> With Python2 you basically have two ways to get a range of numbers:
> range() , which returns a list, and
> xrange() , which returns an iterator.
No. An iterable. As already said, iterators are the ones stopping
forever when the end is reached.
Generally, iterables are allowed to iterate multiple times.
xrange() resp. range() yield iterables.
> The interesting thing to note is that
> xrange() on Python2 runs "considerably" faster than the same code using
> range() on Python3. For large perfect numbers (above 8128) the
> performance difference for perf() is orders of magnitude. Actually,
> range() on Python2 runs somewhat slower than xrange() on Python2, but
> things are much worse on Python3.
That sounds strange at the first glance.
> This is something I never thought to test before Billy's question,
> because I had already decided to work in C for most of my integer
> stuff... like perfects. But now that it sparked my interest, I'm
> wondering if there might be some focus placed on range() performance in
> Python3 for the future, PEP?
I'm sure it is a matter of implementation. You cannot define by PEP what
performance the implementations should have. Maybe range() in 3 is
defined differently to xrange() in 2. I'm not so familiar with 3 to
definitely confirm or decline that. The behaviour, though, seems to be
the same, but range3 (as I call it now) has some more methods than
xrange, like the rich comparison ones. Indexing works with all of them.
Thomas
More information about the Python-list
mailing list