简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM