Skip to content

gh-158803: Borrow bytes items in bytes.join() while the list is locked - #159096

Open
christianaurichzm wants to merge 1 commit into
python:mainfrom
christianaurichzm:gh-158803-join-borrow
Open

christianaurichzm wants to merge 1 commit into
python:mainfrom
christianaurichzm:gh-158803-join-borrow

Conversation

@christianaurichzm

@christianaurichzm christianaurichzm commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #158910 (see #158910 (comment)).

join() increfs every bytes item, and on the free-threaded build that's an atomic op when the items are shared between threads. Since the list is now locked for the whole join, the items can be borrowed instead, like str.join() does. They only need a real reference before the critical section can be suspended: in PyObject_GetBuffer() for non-bytes items, and before PyEval_SaveThread() for results of 1 MiB or more.

Release builds, b",".join(seq) with 8-byte items, median of 5 runs:

FT main FT PR default main default PR
list of 10 168 ns 133 ns 141 ns 121 ns
list of 1000 10.9 µs 7.6 µs 9.7 µs 7.2 µs
8 threads joining one shared list 1.19 s 0.74 s

For reference, the 8-thread case was 1.10 s before #158910. A list where half the items are bytearrays is ~3% slower on both builds.

The existing __buffer__ mutation test used an immortal b'a', so it couldn't catch a freed item; it now uses bytes(2). The new FT test covers the 1 MiB path. Each test fails if its incref is removed. -R 3:3 passes on debug default and FT builds, and TSan is clean for test_free_threading, test_bytes and test_capi.test_bytes.

… locked

bytes.join() and bytearray.join() took a new reference to every exact
bytes item. In the free-threaded build that is an atomic operation on
objects shared between threads, and since pythonGH-158910 it runs while the
list's lock is held.

The critical section keeps the items alive, so borrow them, as
_PyUnicode_JoinArray() does. References are taken only before something
can suspend the critical section: PyObject_GetBuffer() on an item that
is not bytes, or releasing the thread state to copy a large result.
@eendebakpt

Copy link
Copy Markdown
Contributor

@christianaurichzm We can do better by not using the buffers[i] in the case of exact bytes. Core idea: main...eendebakpt:cpython:bytes-join-exact-fast. That gives a speedup of a factor 2x in mainy common cases.

Due to some binary layout changes the uncommon case becomes 10% slower. I was still investigating whether we can resolve that. (if not, I think the PR as is works also).

(feel free to take the branch)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants