6

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?

Boann
  • 48,794
  • 16
  • 117
  • 146
Anton Dovzhenko
  • 2,399
  • 11
  • 16
  • 2
    If in doubt: benchmark. – deceze Apr 01 '20 at 07:16
  • @deceze I appreciate your opinion and doing benchmarks is always a good advice. But if you check answers, there is some story behind how `range` works and its differences in python 2 and 3. So I'd argue and say that this question makes sense. – Anton Dovzhenko Apr 01 '20 at 07:26
  • Wait wait wait why are you doing for i in range (100)? How about just ensure $i$ is an integer and check 0<=i<99? Sorry if this is a stupid suggestion – Gareth Ma Apr 01 '20 at 07:37

3 Answers3

8

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.
codeforester
  • 39,467
  • 16
  • 112
  • 140
xkcdjerry
  • 965
  • 4
  • 15
1

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.

xkcdjerry
  • 965
  • 4
  • 15
Aaron_ab
  • 3,450
  • 3
  • 28
  • 42
0

It won't benefit. If you want to enhance your loop activities refer to the comparison of : https://dev.to/duomly/loops-in-python-comparison-and-performance-4f2m

You can have an idea of how can improve things.

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48