0

I timed both range() and xrange() expecting range() to be faster. But I got surprising results.

$ python -m timeit 'for i in range(1000000):' ' pass'
10 loops, best of 3: 39.9 msec per loop
$ python -m timeit 'for i in xrange(1000000):' ' pass'
10 loops, best of 3: 20.2 msec per loop

If I'm not mistaken, range() stores the whole list in memory while xrange() lazily evaluates the list.

So shouldn't accessing elements from the already generated list be faster than lazily evaluating the list and getting required elements? I don't get it.

Zulan
  • 21,896
  • 6
  • 49
  • 109
Maaverik
  • 193
  • 2
  • 10
  • But to generate all of those elements you have to do the same calculation that `xrange` is doing. The list form of `range` is only more useful when you need that list afterwards, e.g. if you're iterating more than once - see e.g. http://stackoverflow.com/q/135041/3001761 – jonrsharpe Jul 03 '16 at 07:30
  • 1
    Also *"shouldn't accessing elements from the already generated list be faster than lazily evaluating the list and getting required elements"* - that isn't what you're testing. If you want to test that, create the `range` list beforehand and pass it in (not sure how you do `setup` on the command line with `timeit`, but...) – jonrsharpe Jul 03 '16 at 07:32
  • 1
    Pasting this question's exact title into a Google search yields several useful results. In the future, please try that before asking a new question. – TigerhawkT3 Jul 03 '16 at 07:33
  • per: https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Use_xrange_instead_of_range Much of the difference is the implementation in C instead of Python but the xrange function evaluates a range without creating a list of objects for each value in the range. Note also, this only applies to python 2, not python 3 as range in py3 is the same as xrange in py2 and there is no xrange in py3. Some say 'lazy, some say 'efficient' ;) – MmmHmm Jul 03 '16 at 07:36

0 Answers0