Today I observed an interesting behavior using Python.
def f():
ls1 = []
for x in range(1000000):
ls1.append(x)
%timeit f()
77.2 ms ± 1.83 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
And tested a second function.
def f2():
ls1 = []
lsa = ls1.append
for x in range(1000000):
lsa(x)
%timeit f2()
56 ms ± 566 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Assigning append to a variable was faster than using append inside the loop.
Why the second function is faster?