In a Python program which runs a for
loop over a fixed range
many times, e.g.,
while some_clause:
for i in range(0, 1000)
pass
...
does it make sense to cache range
:
r = range(0, 1000)
while some_clause:
for i in r
pass
...
or will it not add much benefit?
Caching is an optimization technique that you can use in your applications to keep recent or often-used data in memory locations that are faster or computationally cheaper to access than their source. Imagine you're building a newsreader application that fetches the latest news from different sources.
LRU (Least Recently Used) Cache discards the least recently used items first. This algorithm requires keeping track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item.
It won't, a range
call does almost nothing. Only the iter
ing part, which is not optional, has a cost.
Interestingly, caching makes it slower for some reason, in the example below.
My benchmarks:
>>> timeit.timeit("""
for i in range(10000):
pass""",number=10000)
1.7728144999991855
>>> timeit.timeit("""
for i in r:
pass""","r=range(10000)",number=10000)
1.80037959999936
And caching it breaks readability, as the Zen of Python states:
Readability counts.
and
Explicit is better than implicit.
Simple is better than complex.
If you are using python 2.*
, range
will return a list
, and you should usexrange
.
xrange
(2.) or range
(3.) are lazy evaluated
, which means it actually evaluated the next requested item when you ask for it.
So, no, no need to cache. Instantiate the range where you need it, no need for tricks and magic there, it's already implemented in Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With