Why is calling eval so slow?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat May 5 12:10:42 EDT 2018
I understand that calling eval() on a string is going to be slow, since
the string has to be parsed, compiled, and then executed.
But why is it so slow when called on function __code__ objects and pre-
compiled byte-code?
Here are the tests I ran:
# calling a regular function
python3.5 -m timeit -s "f = lambda: 99" "f()"
# evaluating a function code object
python3.5 -m timeit -s "f = (lambda: 99).__code__" "eval(f)"
# estimate the overhead of the eval name lookup
python3.5 -m timeit "eval"
# evaluating a pre-compiled byte-code object
python3.5 -m timeit -s "f = compile('99', '', 'eval')" "eval(f)"
# evaluating a string
python3.5 -m timeit "eval('99')"
And the results on my computer:
# call a regular function
1000000 loops, best of 3: 0.245 usec per loop
# evaluate the function __code__ object
1000000 loops, best of 3: 1.16 usec per loop
# overhead of looking up "eval"
10000000 loops, best of 3: 0.11 usec per loop
which means it takes four times longer to execute the code object alone,
compared to calling the function object which executes the code object.
Why so slow?
# evaluate the pre-compiled byte-code
1000000 loops, best of 3: 1.13 usec per loop
# parse, compile and evaluate a string
10000 loops, best of 3: 23.5 usec per loop
That one, at least, makes perfect sense to me :-)
--
Steve
More information about the Python-list
mailing list