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.
The top 3
- Py_BuildValue vs. Direct C API: Up to 2x Slower: Using `Py_BuildValue()` for simple argument packing can be significantly slower than direct C API calls like `PyLong_FromLong()` or `PyTuple_Pack()`. `Py_BuildValue()` incurs overhead from parsing format strings, copying `va_list`, and multiple recursive calls, making direct API functions more efficient for performance-critical code paths.
- Tuple Creation: PyTuple_New + SET_ITEM is Fastest: For optimal performance when creating tuples in C extensions, manually allocating with `PyTuple_New()` and then populating items using `PyTuple_SET_ITEM()` (for new tuples) can be faster than `Py_BuildValue()` or `PyTuple_Pack()`. This method avoids additional overheads and directly manipulates the tuple's internal structure.
- Dictionary Packing: Reference Counting Adds Overhead: When populating Python dictionaries from C using functions like `PyDict_SetItem()` or `PyDict_SetItemString()`, both the key and value objects typically have their reference counts incremented. Developers must explicitly `Py_DECREF()` these temporary objects after insertion to prevent memory leaks, adding a crucial overhead to dictionary packing.
Sources
Open the full topic