Hidden Costs: `eval()`/`exec()` Performance Impact

Beyond security, `eval()` and `exec()` introduce significant performance overhead because they parse and compile the source string into bytecode on every single call. This runtime compilation is a slow process, especially when these functions are used repeatedly within loops. To mitigate this, Python's `compile()` function can pre-compile the code string into a reusable code object, reducing the overhead for subsequent executions. Overall, dynamic code execution is inherently less efficient than executing statically defined code.

The top 3

  1. Direct Execution vs. eval(): Up to 100x Slower: Benchmarking reveals that a simple expression like `eval('1 + 2')` can be approximately 100 times slower than directly executing `1 + 2`, with the significant overhead attributed to the parsing and compilation steps `eval()` performs at runtime.
  2. Code Size Multiplies eval()/exec() Performance Hit: The performance penalty of `eval()` and `exec()` worsens considerably with larger or more complex code, as the runtime parsing and compilation of Python source code into bytecode is an inherently expensive operation.
  3. Optimizing Repeated Calls: The `compile()` Advantage: For code executed frequently, `eval()`'s repeated parsing and compilation creates a significant bottleneck. Using Python's `compile()` function to pre-compile the code string into a reusable code object can yield substantial speedups, reducing execution time by over 35 times in some scenarios.

Sources

Open the full topic