Python Method Call: Up to 21% Slower for Trivial Operations

Calling a Python method can be approximately 11 nanoseconds or 21% slower than a plain function call for trivial 'do-nothing' operations, primarily due to the additional overhead of method binding and the descriptor protocol. This overhead, however, becomes negligible as the complexity of the method's internal operations increases.

The top 3

  1. Python Method Call: Top 3 Internal Overhead Contributors: The primary internal costs of a Python method call stem from the descriptor protocol (binding an instance to a method), dynamic argument unpacking, and the creation of a new execution frame on the call stack, all contributing to slower trivial operations.
  2. Function vs. Method: Python's Performance Gap for Trivial Ops: Direct function calls in Python can be notably faster than instance method calls for trivial operations, with some benchmarks showing methods being around 21% slower for do-nothing calls. This difference arises because method calls involve extra steps like attribute lookup and the descriptor protocol, which direct function calls bypass.
  3. Method Call Top 3: Key internal steps contributing to Python method call overhead include namespace lookup, fetching the function object, and the descriptor protocol invocation for binding.

Sources

Open the full topic