Calling a function is faster than not calling it?

Peter Otten __peter__ at web.de
Sun May 10 06:43:42 EDT 2015


Steven D'Aprano wrote:

> Why is calling a function faster than bypassing the function object and
> evaluating the code object itself? And not by a little, but by a lot?

> Directly eval'ing the code object is easily more than twice as expensive
> than calling the function, but calling the function has to eval the code
> object. That suggests that the overhead of calling the function is
> negative, which is clearly ludicrous.
> 
> I knew that calling eval() on a string was slow, as it has to parse and
> compile the source code into byte code before it can evaluate it, but this
> is pre-compiled and shouldn't have that overhead.
> 
> So what's going on?

A significant part of the extra time is apparently spent on stack 
inspection:

$ python3 -m timeit -s 'f = (lambda: 42); code = f.__code__; ns = {}' 'f()'
10000000 loops, best of 3: 0.179 usec per loop

$ python3 -m timeit -s 'f = (lambda: 42); code = f.__code__; ns = {}' 
'eval(code)'
1000000 loops, best of 3: 0.852 usec per loop

$ python3 -m timeit -s 'f = (lambda: 42); code = f.__code__; ns = {}' 
'eval(code, ns)'
1000000 loops, best of 3: 0.433 usec per loop

$ python3 -m timeit -s 'f = (lambda: 42); code = f.__code__; ns = {}' 'eval; 
ns; f()'
1000000 loops, best of 3: 0.263 usec per loop





More information about the Python-list mailing list