Repository navigation
Open
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetopic-free-threadingtype-bugAn unexpected behavior, bug, or error
Description
Bug report
Extensions built for the stable ABI can't use PyList_SET_ITEM, so they fill new lists with PyList_SetItem. On the free-threaded build each call costs about 2.7x what it does on the GIL-enabled build, while PyTuple_SetItem costs about the same on both builds. Converting native sequences (pointer arrays, vectors) to lists is a hot path for bindings, so this becomes a visible slowdown when a project switches from abi3 to abi3t wheels. For example, in tokenizers a getter that returns three lists runs about 2x slower (see huggingface/tokenizers#2488 (comment)).
Reproducer
fill.c:
#include <Python.h>
static PyObject *fill_list(PyObject *m, PyObject *arg) {
Py_ssize_t n = PyLong_AsSsize_t(arg);
PyObject *list = PyList_New(n);
for (Py_ssize_t i = 0; i < n; i++)
PyList_SetItem(list, i, Py_NewRef(Py_None));
return list;
}
static PyObject *fill_tuple(PyObject *m, PyObject *arg) {
Py_ssize_t n = PyLong_AsSsize_t(arg);
PyObject *tuple = PyTuple_New(n);
for (Py_ssize_t i = 0; i < n; i++)
PyTuple_SetItem(tuple, i, Py_NewRef(Py_None));
return tuple;
}
static PyMethodDef methods[] = {
{"fill_list", fill_list, METH_O, NULL},
{"fill_tuple", fill_tuple, METH_O, NULL},
{NULL},
};
PyABIInfo_VAR(abi_info);
static PySlot slots[] = {
PySlot_DATA(Py_mod_abi, &abi_info),
PySlot_DATA(Py_mod_name, "fill"),
PySlot_STATIC_DATA(Py_mod_methods, methods),
PySlot_DATA(Py_mod_gil, Py_MOD_GIL_NOT_USED),
PySlot_END,
};
PyMODEXPORT_FUNC PyModExport_fill(void) { return slots; }bench.py:
import sys, timeit, fill
n = 1000
print(sys.version.split()[0], "free-threaded" if not sys._is_gil_enabled() else "GIL", fill.__file__.rsplit("/", 1)[-1])
for name in ("fill_list", "fill_tuple"):
f = getattr(fill, name)
t = min(timeit.repeat(lambda: f(n), number=2000, repeat=9)) / 2000
print(f" {name}: {t / n * 1e9:.1f} ns/item")Build one copy for abi3 and one for abi3t, then run them:
mkdir abi3 abi3t
gcc -O2 -shared -fPIC -DPy_LIMITED_API=0x030f0000 -I"$(python3.15 -c 'import sysconfig; print(sysconfig.get_path("include"))')" fill.c -o abi3/fill.abi3.so
gcc -O2 -shared -fPIC -DPy_TARGET_ABI3T=0x030f0000 -I"$(python3.15t -c 'import sysconfig; print(sysconfig.get_path("include"))')" fill.c -o abi3t/fill.abi3t.so
PYTHONPATH=abi3 python3.15 bench.py
PYTHONPATH=abi3t python3.15 bench.py
PYTHONPATH=abi3t python3.15t bench.pyResults
3.15.0rc2, x86-64 Linux, gcc -O2:
3.15.0rc2 GIL fill.abi3.so
fill_list: 7.2 ns/item
fill_tuple: 7.6 ns/item
3.15.0rc2 GIL fill.abi3t.so
fill_list: 6.6 ns/item
fill_tuple: 7.5 ns/item
3.15.0rc2 free-threaded fill.abi3t.so
fill_list: 19.8 ns/item
fill_tuple: 9.6 ns/item
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Linked PRs
- gh-158660: Add
PyListBuilderC API #160127 - gh-158660: Avoid locking for new lists with preallocated space #160156
- gh-158660: Test PyList_New() check on integer overflow #162704
- [3.15] gh-158660: Test PyList_New() check on integer overflow (GH-162704) #162739
- [3.14] gh-158660: Test PyList_New() check on integer overflow (GH-162704) #162740
Reacted by Brittany Reynoso
Metadata
Metadata
Assignees
Labels
interpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetopic-free-threadingtype-bugAn unexpected behavior, bug, or error
Activity
vstinner commentedon Oct 20, 2026
Python 3.15 adds https://docs.python.org/dev/c-api/tuple.html#c.PyTuple_FromArray which creates a tuple object from a C array of objects. Do you need a function similar to that?
Or do you need an API to modify a list, something like
PyList_ExtendFromArray()?ngoldbaum commentedon Oct 20, 2026
PyList_FromArrayhelps when there is a native array already built but doesn't help with an iterator or other data stream that should be converted into a list. That's why I think a builder API likePyBytesWriteris the most useful thing.pitrou commentedon Oct 21, 2026
Either that or a batched function such as:
int PyList_SetItems(PyObject* list, Py_ssize_t start, PyObject** items, Py_ssize_t nitems)A batched function allows using a stack-allocated array for
items(of whatever size the caller finds comfortable), eliminating any intermediate allocation.Note that a builder API would also benefit from allowing batched append calls.
pythongh-158660: Add PyListWriter C API
pythongh-158660: Add `PyListWriter` C API
corona10 commentedon Oct 21, 2026
Maybe we can reconsider dictonary for this kind of pattern?
For frozendict: https://peps.python.org/pep-0839/
vstinner commentedon Oct 21, 2026
I created #160127 to add a new
PyListWriterC API. It's similar to thePyListC API, but it avoids locking the list to append items.pythongh-158660: Add `PyFrozenSetWriter` C API
pythongh-158660: Add `PyFrozenSetWriter` C API
vstinner commentedon Oct 22, 2026
If a new API is added (such as proposed
PyListWriter), IMO it should be added to the limuted C API, since such API would be added to fix the abi3t performance issue.vstinner commentedon Oct 22, 2026
An alternative to #160127
PyListWriterAPI withPyListWriter_Append()/PyListWriter_Extend()functions would be to design aPyListWriterAPI exposing a rawPyObject **array, similar toPyBytesWriter_Create()andPyLongWriter_Create()do. But I'm less excited by a "raw" array ofPyObject*since such API would be more error prone. The caller would be responsible to set all items, handle reference counting, and check the array bounds.espressolee commentedon Oct 25, 2026
Some numbers from Apple silicon (arm64 macOS, release builds without PGO, Apple clang 21), in case aarch64 looks different from x86. Same workload as the
fill_listreproducer above (list ofNoneviaPyList_New(n)+PyList_SetItem), extension built against each tree. ns/item at n=1000, median of 5 rounds (each round = min of 11 repeats); the 16 configurations were interleaved and order-rotated across rounds. "limited" is abi3 on the GIL build and abi3t on the FT build.PyList_SetItemon the merge-base is smaller here than in the x86 numbers in the issue: 1.4x limited, 1.7x non-limited.PyList_SetItemis 26% faster non-limited and 18% faster with abi3t; all five per-round FT ratios were below 0.92. GIL ratios were 0.94–1.01.PyList_SET_ITEM, which the PR also touches, had median ratios within 3% of 1.PyListBuilderC API #160127: I couldn't resolve an effect on the existing paths against aff7a2e.AppendStealis about 2x faster than theSetItemloop and 1.8x slower than theSET_ITEMloop; the bulkExtendArraycall measured lower ns/item than theSET_ITEMloop.PyListBuilderC API #160127 GIL builds, so I wouldn't read anything into small GIL differences. n=10 and n=100 point the same way.pythongh-158660: Add `PySetBuilder` C API
pythongh-158660: Add `PySetBuilder` C API
pythongh-158660: Add `PySetBuilder` C API
vstinner commentedon Nov 24, 2026
When building a set,
PySet_Add()suffers from the same performance issue thanPyList_Add()on Free Threading: each call needs a critical section. I created PR gh-162582 which addsPySetBuilderC API to create set and frozenset objects.gh-158660: Test PyList_New() check on integer overflow (#162704)
[3.14] gh-158660: Test PyList_New() check on integer overflow (GH-162704
[3.15] gh-158660: Test PyList_New() check on integer overflow (GH-162704
markshannon commentedon Nov 30, 2026
I think the array based APIs are the way to go.
Let's add four new functions:
Being simpler makes it easier to use correctly, and there's less code to maintain than
PyListWriterThe two
PyList_FromArrayfunction need no synchronization, and thePyList_Extendfunctions only one locking operation per array, so they should be quick.vstinner commentedon Nov 30, 2026
About
PyList_ExtendArray()andPyList_ExtendArraySteal(): addingPyListBuilder_Append()was a friction point in capi-workgroup/decisions#118 discussion. In short, the majority of C functions building lists currently callPyList_Append(). Rewriting a function to add multiple items at once make the code more complex and more error-prone (example).PyListBuilderis mostly a trade-off between usability and performance.PyList_FromArray()andPyList_FromArraySteal()are interesting, but I'm not sure how many existing C functions can be modified to easily adopt such API. Currently, the closest code pattern isPyList_New()+PyList_SET_ITEM()which is implemented more or less as "allocate an array of objects and fill the array":Note:
PyList_New()is different thanPyListBuilder_Create(): it immediately tracks the list in the GC.Note:
PyList_SET_ITEM()macro is kind of special, it doesn't use atomic operation to store the item, and it doesn't use a critical section on the list. It requires that the list is not exposed to other C functions and to Python (but the list is already tracked by the GC!).Using
PyList_FromArray()here would need to allocate an array on the heap, a loop to clear the array on error, and free the array memory (on success and on error). Something like that:Not all functions are "really" performance critical, but I don't think that we should apply above
PyList_FromArraySteal()pattern to all functions.Hopefully, if you know that the array is small enough (fixed size and the size is "small"), you can allocate it on the stack (which avoid the
PyMemcalls and removes the "memory allocation failure" code path).davidhewitt commentedon Nov 30, 2026
I would have assumed that a decent win of the
PyListBuilderAPI is that it can keep the benefit of being able to take the size hint likePyList_New.PyList_FromArray/PyList_ExtendArraymay require multiple reallocations of the list to eventually extend the storage to the final size (unless it's reasonable to preallocate the entire array outside the list up-front first and then callFromArrayonce, which I doubt it is for arbitrarily large lists).vstinner commentedon Nov 30, 2026
By the way, currently when calling
PyList_New(prealloc) + PyList_Extend(<small tuple>) + PyList_Extend(<large tuple>), the firstPyList_Extend()shrinks the list to<small tuple>size which defeats the purpose of preallocatingpreallocitems, the second andPyList_Extend()has to enlarge the array (again!). At this point, it's unclear to me if this behavior is made on purpose (reduce memory consumption) or if it's a bug. See: #160127 (comment). At least, inPyListBuilderAPI, we can handle this case differently since we know that we are building a new list and that we don't want to shrink beforePyListBuilder_Finish().vstinner commentedon Nov 30, 2026
@markshannon: By the way, I made the assumption that you made a mistake and you propose this API instead: