Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions Lib/test/test_bytes.py
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,7 @@ def test_join(self):
self.assertEqual(self.type2test(b"").join(lst), b"abc")
self.assertEqual(self.type2test(b"").join(tuple(lst)), b"abc")
self.assertEqual(self.type2test(b"").join(iter(lst)), b"abc")
self.assertEqual(self.type2test(b".").join([b"ab", b"cd"]), b"ab.cd")
dot_join = self.type2test(b".:").join
self.assertEqual(dot_join([b"ab", b"cd"]), b"ab.:cd")
self.assertEqual(dot_join([memoryview(b"ab"), b"cd"]), b"ab.:cd")
Expand All @@ -654,6 +655,8 @@ def test_join(self):
seq = [b"abc"] * 100000
expected = b"abc" + b".:abc" * 99999
self.assertEqual(dot_join(seq), expected)
seq = [bytearray(b"abc")] * 100000
self.assertEqual(dot_join(seq), expected)
# Stress test with empty separator
seq = [b"abc"] * 100000
expected = b"abc" * 100000
Expand All @@ -671,12 +674,13 @@ def test_join_concurrent_buffer_mutation(self):
# mutate the joined sequence (simulated here by mutating in __buffer__).
# See: https://github.com/python/cpython/issues/151295
def make_seq(mutate):
# Item is only referenced from the list slot, so mutate() frees it.
# The first two items are only referenced from their list slots,
# so mutate() frees them.
class Item:
def __buffer__(self, flags):
mutate(seq)
return memoryview(b'x')
seq = [b'a', Item(), b'c']
seq = [bytes(2), Item(), b'c']
return seq

for sep in (self.type2test(b''), self.type2test(b'::')):
Expand All @@ -686,11 +690,11 @@ def __buffer__(self, flags):
self.assertRaises(RuntimeError, sep.join, seq)

# The list length is unchanged, so the size-change recheck
# cannot fire: only keeping the item alive avoids the crash.
# cannot fire: only keeping the items alive avoids the crash.
def replace(seq):
seq[1] = b'z'
seq[0] = seq[1] = b'z'
seq = make_seq(replace)
self.assertEqual(sep.join(seq), sep.join([b'a', b'x', b'c']))
self.assertEqual(sep.join(seq), sep.join([bytes(2), b'x', b'c']))

def test_count(self):
b = self.type2test(b'mississippi')
Expand Down
21 changes: 21 additions & 0 deletions Lib/test/test_free_threading/test_bytes_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,27 @@ def reader():

threading_helper.run_concurrently([writer] + [reader] * 4)

def test_racing_join_replace_large(self):
# join() suspends the critical section while it copies a result
# of 1 MiB or more, so the list can drop its items meanwhile.
size = 1 << 18
lst = [bytes(size) for _ in range(8)]
done = Event()

def writer():
try:
for _ in range(100):
for i in range(len(lst)):
lst[i] = bytes(size)
finally:
done.set()

def reader():
while not done.is_set():
self.assertEqual(b''.join(lst), bytes(size * len(lst)))

threading_helper.run_concurrently([writer] + [reader] * 4)


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Speed up :meth:`bytes.join` and :meth:`bytearray.join` when all items are
:class:`bytes`. Patch by Pieter Eendebak and Christian Aurich Zanettini
Martins.
51 changes: 49 additions & 2 deletions Objects/stringlib/join.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,44 @@ STRINGLIB(bytes_join_lock_held)(PyObject *sep, PyObject *seq)
}
}
#endif

Py_ssize_t limit = GIL_THRESHOLD - seplen;
for (i = 0; i < seqlen; i++) {
item = PySequence_Fast_GET_ITEM(seq, i);
if (!PyBytes_CheckExact(item)
|| PyBytes_GET_SIZE(item) >= limit - sz) {
break;
}
sz += PyBytes_GET_SIZE(item) + seplen;
}
/* Fast path: all items are exact bytes and the result is too small to
* release the GIL for. Nothing here runs Python code or suspends the
* critical section, so seq keeps the items alive and they can be copied
* without taking references. */
if (i == seqlen) {
Comment thread
vstinner marked this conversation as resolved.
res = STRINGLIB_NEW(NULL, sz - seplen);
if (res == NULL) {
return NULL;
}
p = STRINGLIB_STR(res);
for (i = 0; i < seqlen; i++) {
if (i != 0 && seplen != 0) {
if (seplen == 1) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it really worth it to specialize this case? If you remove it, you can also remove seplen != 0 test above.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I measured it, and both checks pay for themselves. Without the seplen == 1 branch, b",".join() on 1000 items goes from 4.3 µs to 6.3 µs. Dropping seplen != 0 as well takes b"".join() from 3.8 µs to 6.3 µs. With a two-byte separator neither one makes a difference. That's on a PGO+LTO default build with pyperf, builds alternated over 20 rounds.

*p++ = *sepstr;
}
else {
memcpy(p, sepstr, seplen);
p += seplen;
}
}
item = PySequence_Fast_GET_ITEM(seq, i);
memcpy(p, PyBytes_AS_STRING(item), PyBytes_GET_SIZE(item));
p += PyBytes_GET_SIZE(item);
Comment on lines +67 to +69

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PySequence_Fast_GET_ITEM(), PyBytes_AS_STRING() and PyBytes_GET_SIZE() cannot raise exception, they only get a member of their C structure. Would it be insane to call them with the GIL released to support size > GIL_THRESHOLD?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not on this path, no. The getters themselves are fine, the problem is that the items are borrowed from a list that other threads can see. Once the GIL is released (or on the FT build, once the thread detaches and the critical section gets suspended), another thread can replace items or resize the list while we're still copying. Results over 1 MiB already go through the general path, which takes a reference and saves the buffer pointer for every item before releasing the GIL. To do it here we'd need a snapshot of the items, or a separate path just for tuples.

}
return res;
}
sz = 0;

if (seqlen > NB_STATIC_BUFFERS) {
buffers = PyMem_NEW(Py_buffer, seqlen);
if (buffers == NULL) {
Expand Down Expand Up @@ -148,8 +186,17 @@ STRINGLIB(bytes_join_lock_held)(PyObject *sep, PyObject *seq)
error:
res = NULL;
done:
for (i = 0; i < nbufs; i++)
PyBuffer_Release(&buffers[i]);
for (i = 0; i < nbufs; i++) {
PyObject *obj = buffers[i].obj;
if (obj != NULL && PyBytes_CheckExact(obj)) {
/* Same as PyBuffer_Release(), without the call: bytes has no
* bf_releasebuffer, so only the reference to obj is dropped. */
Py_DECREF(obj);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand this change. Is it really needed?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is for performance. If we accept a minor performance loss for the non-exact bytes we can remove this. I would be fine with.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's an optimization, please add a comment explaining it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It skips the generic PyBuffer_Release() path for exact bytes, since they have no bf_releasebuffer. On my FT PGO+LTO builds, taking it out made "999 bytes + 1 bytearray" about 6% slower, but it also moved some fast-path timings that never reach this loop, so I can't really tell how much of that is the shortcut. I added a comment in ec07466. Happy to drop it if you'd rather have the simpler code.

}
else {
PyBuffer_Release(&buffers[i]);
}
}
if (buffers != static_buffers)
PyMem_Free(buffers);
return res;
Expand Down
Loading