Function Calls: Heavy Stack Frame Creation Overhead

Each Python function call incurs significant overhead by creating and pushing a new 'stack frame' onto the call stack. This frame stores arguments, local variables, and the execution context, a process that is much heavier and slower than a direct function call in compiled languages like C.

The top 3

  1. Python vs. C Call: Stack Frame Overhead Ratio: Python function calls are significantly slower than C, with benchmarks showing Python calls taking around 150ns, allowing only millions of calls per second. This stark difference stems from Python's dynamic typing requiring "boxing" and "unboxing" of values, and extensive setup of its `PyFrameObject`, unlike C's simpler, often inlined, stack operations.
  2. Python Frame Overhead: Top 3 Key Contributors: Python's `PyFrameObject` creation involves significant overhead from dynamic memory allocation, dictionary lookups for local and global variables, and extensive setup for argument parsing and exception handling.
  3. Python Call Speedup: Top 3 Optimization Methods: CPython reduces function call overhead using 'fast locals' for direct array access and specialized bytecode instructions, while JIT compilers like PyPy significantly speed up execution through techniques like frame elision.

Sources

Open the full topic