Python--Faster-Way icon indicating copy to clipboard operation
Python--Faster-Way copied to clipboard

xrange vs range

Open endophage opened this issue 9 years ago • 1 comments

In almost every instance you use range, you should instead be using xrange. Test 16 is especially painful to look at as range(1000) already creates an array with the integers 0 to 999, which you then iterate over to create another copy of the array.

Test 16 should really be a comparison of the two versions you have (but using xrange instead of range), vs just "return range(1000)". A quick test on my system shows a simple "return range(1000)" to be a further 3-4x faster than your fastest Test 16 variant, and substituting xrange for range achieves a 20-30% improvement over your fastest variant.

endophage avatar Dec 31 '14 18:12 endophage

from timeit import timeit
>>> def a():
...     return [i for i in range(1000)]
...
>>> def b():
...     return range(1000)
...
>>> def c():
...     return [i for i in xrange(1000)]
...
>>> timeit(a, number=100000)
2.728806972503662
>>> timeit(b, number=100000)
0.723524808883667
>>> timeit(c, number=100000)
2.2922120094299316

endophage avatar Dec 31 '14 18:12 endophage