Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

xrange vs range #6

Open
endophage opened this issue Dec 31, 2014 · 1 comment
Open

xrange vs range #6

endophage opened this issue Dec 31, 2014 · 1 comment

Comments

@endophage
Copy link

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant