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.

The top 3

  1. Descriptor Protocol: Method Lookup's Hidden Cost: Python's descriptor protocol, specifically the `__get__` method, is invoked when a method is accessed via an instance. This dynamic process creates a 'bound method' object on demand, wrapping the original function and the instance, which introduces a lookup and creation overhead not present in direct function calls.
  2. Bound Method Creation: An Object Allocation Tax: Each time a method is accessed through an instance, Python creates a new, temporary 'bound method' object. This object is a thin wrapper that stores references to both the original function and the specific instance (`self`), incurring a small but measurable cost for object allocation and setup that pure function calls avoid.
  3. Explicit 'self' Handling: Method Call's Argument Overhead: The explicit `self` argument in method definitions, though automatically passed by Python during invocation, necessitates additional internal processing. This involves retrieving the instance and inserting it as the first argument, a step that adds overhead compared to functions which only process the arguments explicitly provided in their call signature.

Sources

Open the full topic