Skip to content

PyList_SetItem is ~2.7x slower per item on the free-threaded build #158660

Open

Description

@ngoldbaum

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.py

Results

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

Activity

  1. vstinner commented on Oct 20, 2026

    @vstinner
    Member

    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()?

  2. ngoldbaum commented on Oct 20, 2026

    @ngoldbaum
    ContributorAuthor

    PyList_FromArray helps 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 like PyBytesWriter is the most useful thing.

  3. pitrou commented on Oct 21, 2026

    @pitrou
    Member

    PyList_FromArray helps 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 like PyBytesWriter is the most useful thing.

    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.

  4. added 2 commits that reference this issue on Oct 21, 2026
  5. corona10 commented on Oct 21, 2026

    @corona10
    Member

    Maybe we can reconsider dictonary for this kind of pattern?
    For frozendict: https://peps.python.org/pep-0839/

  6. vstinner commented on Oct 21, 2026

    @vstinner
    Member

    I created #160127 to add a new PyListWriter C API. It's similar to the PyList C API, but it avoids locking the list to append items.

  7. added 2 commits that reference this issue on Oct 21, 2026
  8. vstinner commented on Oct 22, 2026

    @vstinner
    Member

    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.

  9. vstinner commented on Oct 22, 2026

    @vstinner
    Member

    An alternative to #160127 PyListWriter API with PyListWriter_Append() / PyListWriter_Extend() functions would be to design a PyListWriter API exposing a raw PyObject **array, similar to PyBytesWriter_Create() and PyLongWriter_Create() do. But I'm less excited by a "raw" array of PyObject* 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.

  10. espressolee commented on Oct 25, 2026

    @espressolee
    Contributor

    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_list reproducer above (list of None via PyList_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.

                                             GIL    FT
    gh-160156 merge-base 4036afb, limited   5.35   7.30
    gh-160156 merge-base 4036afb, non-lim   3.07   5.14
    gh-160156 ff50ed2, limited              5.29   5.98
    gh-160156 ff50ed2, non-limited          2.96   3.80
    
    gh-160127 da86200 (merge-base aff7a2e), non-limited, FT, all within that build:
      PyList_SetItem loop                   5.16
      PyList_SET_ITEM loop                  1.43
      PyListWriter_AppendSteal loop         2.58
      PyListWriter_ExtendArray (one call)   1.09
    
    • The FT/GIL gap for PyList_SetItem on the merge-base is smaller here than in the x86 numbers in the issue: 1.4x limited, 1.7x non-limited.
    • gh-158660: Avoid locking for new lists with preallocated space #160156: FT PyList_SetItem is 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.
    • gh-158660: Add PyListBuilder C API #160127: I couldn't resolve an effect on the existing paths against aff7a2e. AppendSteal is about 2x faster than the SetItem loop and 1.8x slower than the SET_ITEM loop; the bulk ExtendArray call measured lower ns/item than the SET_ITEM loop.
    • A tuple control that neither PR touches moved by up to ~13% between the gh-158660: Add PyListBuilder C API #160127 GIL builds, so I wouldn't read anything into small GIL differences. n=10 and n=100 point the same way.
  11. added 3 commits that reference this issue on Nov 24, 2026
  12. vstinner commented on Nov 24, 2026

    @vstinner
    Member

    When building a set, PySet_Add() suffers from the same performance issue than PyList_Add() on Free Threading: each call needs a critical section. I created PR gh-162582 which adds PySetBuilder C API to create set and frozenset objects.

  13. added 3 commits that reference this issue on Nov 27, 2026
  14. markshannon commented on Nov 30, 2026

    @markshannon
    Member

    I think the array based APIs are the way to go.

    Let's add four new functions:

    • PyList_FromArray(PyObject *list, PyObject **array, uintptr_t size)
    • PyList_FromArraySteal(PyObject *list, PyObject **array, uintptr_t size)
    • PyList_ExtendArray(PyObject *list, PyObject **array, uintptr_t size)
    • PyList_ExtendArraySteal(PyObject *list, PyObject **array, uintptr_t size)

    Being simpler makes it easier to use correctly, and there's less code to maintain than PyListWriter

    The two PyList_FromArray function need no synchronization, and the PyList_Extend functions only one locking operation per array, so they should be quick.

  15. vstinner commented on Nov 30, 2026

    @vstinner
    Member

    About PyList_ExtendArray() and PyList_ExtendArraySteal(): adding PyListBuilder_Append() was a friction point in capi-workgroup/decisions#118 discussion. In short, the majority of C functions building lists currently call PyList_Append(). Rewriting a function to add multiple items at once make the code more complex and more error-prone (example). PyListBuilder is mostly a trade-off between usability and performance.


    PyList_FromArray() and PyList_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 is PyList_New() + PyList_SET_ITEM() which is implemented more or less as "allocate an array of objects and fill the array":

            np = PyList_New(slicelen);
            if (np == NULL)
                return NULL;
    
            for (...) {
                PyObject *v = ...;
                if (v == NULL) {
                    Py_DECREF(np);
                    return NULL;
                }
                PyList_SET_ITEM(np, i, v);
            }
            return np;

    Note: PyList_New() is different than PyListBuilder_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:

            PyObject **array = PyMem_New(PyObject*, slicelen);
            if (array == NULL) {
                PyErr_NoMemory();
                return NULL;
            }
    
            for (i = 0; i < slicelen; i++) {
                array[i] = ...;
                if (v == NULL) {
                    for (Py_ssize_t j=0; j < i; i++) {
                        Py_DECREF(array[j]);
                    }
                    PyMem_Free(array);
                    return NULL;
                }
            }
    
            PyObject *np = PyList_FromArraySteal(array, slicelen);
            PyMem_Free(array);
            return np;

    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 PyMem calls and removes the "memory allocation failure" code path).

  16. davidhewitt commented on Nov 30, 2026

    @davidhewitt
    Contributor

    I would have assumed that a decent win of the PyListBuilder API is that it can keep the benefit of being able to take the size hint like PyList_New.

    PyList_FromArray / PyList_ExtendArray may 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 call FromArray once, which I doubt it is for arbitrarily large lists).

  17. vstinner commented on Nov 30, 2026

    @vstinner
    Member

    By the way, currently when calling PyList_New(prealloc) + PyList_Extend(<small tuple>) + PyList_Extend(<large tuple>), the first PyList_Extend() shrinks the list to <small tuple> size which defeats the purpose of preallocating prealloc items, the second and PyList_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, in PyListBuilder API, we can handle this case differently since we know that we are building a new list and that we don't want to shrink before PyListBuilder_Finish().

  18. vstinner commented on Nov 30, 2026

    @vstinner
    Member

    @markshannon: By the way, I made the assumption that you made a mistake and you propose this API instead:

    PyObject* PyList_FromArray(PyObject **array, uintptr_t size)
    PyObject* PyList_FromArraySteal(PyObject **array, uintptr_t size)
    int PyList_ExtendArray(PyObject *list, PyObject **array, uintptr_t size)
    int PyList_ExtendArraySteal(PyObject *list, PyObject **array, uintptr_t size)
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coreperformancetopic-free-threadingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions