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
barrefers to, and the name binding might change at any time.If in doubt, simply measure the performance yourself — the
timeitmodule is your friend.