Tianyang Li
Tianyang Li

Reputation: 1785

Python: call the same function with the same arguments several times, or save the result as an intermediate value?

If I have a function

def bar(n):
    return n**100

Would there be a performance difference between

for i in range(1000000):
    x = bar(30)
    # use x for something

and

x = bar(30)
# use x for something 1,000,000 times

I don't know if the interpreter has been optimized for cases like this?

Upvotes: 1

Views: 980

Answers (2)

Roland Smith
Roland Smith

Reputation: 43505

Depends on the implementation. Pypy added loop invariant code motion in version 1.5.

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601869

The CPython compiler only does very few simple peephole optimisations, but it will certainly never optimise away a function call -- how would it know if the function has side effects anyway? At compilation time, it usually doesn't even know which function the name bar refers to, and the name binding might change at any time.

If in doubt, simply measure the performance yourself -- the timeit module is your friend.

Upvotes: 5

Related Questions