Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it worth caching Python's range(start, stop, step)? [duplicate]

Tags:

python

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?

like image 710
Anton Dovzhenko Avatar asked Apr 01 '20 07:04

Anton Dovzhenko


People also ask

What is caching in Python?

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.

What is LRU cache Python?

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.


2 Answers

It won't, a range call does almost nothing. Only the itering 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.
like image 144
xkcdjerry Avatar answered Oct 18 '22 19:10

xkcdjerry


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.

like image 34
Aaron_ab Avatar answered Oct 18 '22 19:10

Aaron_ab