Python's Slowest Basic Ops: Attribute Access & Function Calls
Attribute access and function calls are among the most impacted basic operations in Python due to dynamic typing. Accessing attributes often involves dictionary lookups (e.g., `__dict__`) and method calls require dynamic dispatch, both adding significant overhead compared to direct memory access or function pointers in compiled languages.
The top 3
- Attribute Access: The `__dict__` Lookup Tax & MRO Cost: Python objects typically store attributes in a dynamic dictionary (`__dict__`), making attribute access a hash table lookup, which is inherently slower than direct memory access in compiled languages. For inherited attributes, Python must also traverse the Method Resolution Order (MRO) of classes, further increasing lookup overhead.
- 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.
- 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.
Sources
Open the full topic