Why is a function/method call in python expensive?

VGonPa picture VGonPa · Apr 6, 2014 · Viewed 10.5k times · Source

In this post, Guido van Rossum says that a function call may be expensive, but I do not understand why nor how much expensive can be.

How much delay adds to your code a simple function call and why?

Answer

Martijn Pieters picture Martijn Pieters · Apr 6, 2014

A function call requires that the current execution frame is suspended, and a new frame is created and pushed on the stack. This is relatively expensive, compared to many other operations.

You can measure the exact time required with the timeit module:

>>> import timeit
>>> def f(): pass
... 
>>> timeit.timeit(f)
0.15175890922546387

That's 1/6th of a second for a million calls to an empty function; you'd compare the time required with whatever you are thinking of putting in a function; the 0.15 second would need to taken into account, if performance is an issue.