1

What is faster: Reading the same value from a list multiple times or saving the value to a new variable? My code looks something like this:

if list[0] > foo:
    return list[0], list[0] + bar

Should I define l0 = list[0] to avoid reading the list three times? Or is this inefficient because of memory allocation and garbage collection for the l0 variable?

Elias Strehle
  • 1,722
  • 1
  • 21
  • 34
  • Is this really a bottleneck in your code? – Chris_Rands Mar 23 '18 at 10:12
  • 1
    Since [Python lists are array-based](https://stackoverflow.com/questions/3917574/how-is-pythons-list-implemented), the difference will most likely be negligible in any case. For practical purposes it will probably always be more relevant which way is more readable or less error-prone. I suppose the question is technically valid, though, if only as a curiosity. – jdehesa Mar 23 '18 at 10:21

1 Answers1

2

I agree with the comments, this kind of micro-optimizations are unlikely to be worth the effort. Anyway, it's easy to check things like this using python's timeit https://docs.python.org/3.6/library/timeit.html

from timeit import timeit

def a():
    if my_list[0] == 0:
        return my_list[0], my_list[0] + 42
    return 'bar'

def b():
    my_list_0 = my_list[0]
    if my_list_0 == 0:
        return my_list_0, my_list_0 + 42
    return 'bar'

timeit(a)
>>> 0.01871770019934047

timeit(b)
>>> 0.01709997310099425
JoseKilo
  • 2,343
  • 1
  • 16
  • 28