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

Viewed 123

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?

3 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.

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.

Related