0

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?

2 Answers 2

2

Python is a dynamic language. Attribute lookup is comparable to a dict lookup, so in the first scenario, you first lookup ls1 in the local scope and then lookup append on the ls1-object each of 1000000 iterations. In the second scenario you lookup the append on ls1 only once, and then 1 million iterations where you lookup lsa in the local scope

Sign up to request clarification or add additional context in comments.

Comments

2

Because in the second function, you have the reference to the method already and can call it directly in every iteration, whereas in the first function, it has to first find the append method of the ls1 object first in every iteration before making the call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.