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.
The top 3
- Descriptor Protocol: Method Binding Cost: Invoking a method like `obj.method()` triggers the descriptor protocol, where the function's `__get__` method is called to bind it to the instance, creating a temporary bound method object. This adds an extra function call and object creation overhead for every method invocation.
- Dynamic Attribute Lookup: MRO Traversal: Before a method can be called, Python must dynamically locate the method attribute within the object's Method Resolution Order (MRO). This involves dictionary lookups for each class in the MRO, which is significantly slower than direct memory access in compiled languages like C.
- Argument Packing/Unpacking: Tuple & Dict Creation: Python method calls often incur overhead from packing positional arguments into tuples and keyword arguments into dictionaries, even for simple calls. This involves memory allocation and object creation, which can be avoided in languages with direct parameter passing.
Sources
Open the full topic