Method Invocation: Descriptor Protocol & Binding Cost

Method calls in Python are a specific type of attribute access that involves additional overhead due to the descriptor protocol. This protocol (e.g., `__get__`) is used to bind a method to its instance at runtime, adding extra steps beyond a simple attribute lookup and making them slower than direct attribute access or simple function calls.

The top 3

  1. 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.
  2. Descriptor Protocol: The Multi-Step Method Lookup Process: Python's descriptor protocol adds layers of indirection to method invocation; when `obj.method()` is called, the interpreter first checks if 'method' is a data descriptor in the class. If so, its `__get__` method is invoked to bind the function to the instance, creating a `MethodType` object, rather than directly accessing an instance attribute, which contributes to performance overhead.
  3. `__slots__`: Up to 20% Faster Attribute Access by Bypassing `__dict__`: Using `__slots__` in Python classes can improve attribute access speed by 10-20% and reduce memory usage by preventing the creation of an instance `__dict__` for each object. This optimization, originally a fallback for new-style class performance, directly reserves space for declared attributes, bypassing slower dictionary lookups.

Sources

Open the full topic