I was doing a couple of tests, and found that xrange()
is MUCH faster than range()
(as confirmed by various questions/answers as well):
>>> from timeit import timeit
>>> timeit(stmt = 'x = range(1000)', number = 10000)
0.38216601211680734
>>> timeit(stmt = 'x = xrange(1000)', number = 10000)
0.010537726631953959 # xrange is much faster than range
I got curious, so I tried another test, to see if list(xrange(1000))
would still be faster than simply range(1000)
:
>>> timeit(stmt = 'x = range(1000)', number = 10000)
0.3858838963796529
>>> timeit(stmt = 'x = list(xrange(1000))', number = 10000)
0.492734766028903 # now, xrange is slower
This is also true for more calls:
>>> timeit(stmt = 'x = range(1000)', number = 100000)
3.6457308233315757
>>> timeit(stmt = 'x = list(xrange(1000))', number = 100000)
5.722031755612818
So, my question is, why is list(xrange)
significantly slower than range
itself?
I saw this question on the slowness of list()
, dict()
, and other constructor methods, so is that why list(xrange)
is so much slower?
Using dis.dis()
, I found that list(xrange)
performs more computations than range
):
>>> dis.dis('x = list(xrange(1000))')
0 SETUP_LOOP 15648 (to 15651)
3 SLICE+2
4 IMPORT_NAME 29545 (29545)
7 LOAD_GLOBAL 30760 (30760)
10 POP_JUMP_IF_FALSE 28257
13 BUILD_LIST 10341
16 <49>
17 <48>
18 <48>
19 <48>
20 STORE_SLICE+1
21 STORE_SLICE+1
>>> dis.dis('x = range(1000)')
0 SETUP_LOOP 15648 (to 15651)
3 SLICE+2
4 POP_JUMP_IF_FALSE 28257
7 BUILD_LIST 10341
10 <49>
11 <48>
12 <48>
13 <48>
14 STORE_SLICE+1