Skip to content

Commit f2ceace

Browse files
committed
gh-158585: Optimize bytes object creation
Add bytes_alloc() helper function. bytes_alloc() and _PyBytes_FromStringAndSize() have less conditional branches than previous code, and so should be a little bit faster. * Rename existing bytes_alloc() to bytes_type_alloc(). * Replace _PyBytes_FromSize(calloc=1) with _PyBytes_FromSizeZero(). * Add set_ob_shash_unsafe(): similar to set_ob_shash() but don't use an atomic operation on Free Threading. Use this new function on newly allocated bytes objects and in bytes_resize_inplace(). * Replace PyBytes_FromStringAndSize(NULL, size) with bytes_alloc(size). * Use bytes_alloc() in PyBytes_FromString() and _PyBytes_Repeat(). * Add _PyBytes_FromStringAndSize(): similar to PyBytes_FromStringAndSize(), but str must not be NULL. * Replace PyBytes_FromStringAndSize() with _PyBytes_FromStringAndSize(). * Test that PyBytes_FromString() and PyBytes_FromStringAndSize() return singletons for 0 or 1 bytes.
1 parent 9a15440 commit f2ceace

2 files changed

Lines changed: 130 additions & 88 deletions

File tree

‎Lib/test/test_capi/test_bytes.py‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,12 @@ def test_fromstringandsize(self):
6161
self.assertEqual(fromstringandsize(b'abc'), b'abc')
6262
self.assertEqual(fromstringandsize(b'abc', 2), b'ab')
6363
self.assertEqual(fromstringandsize(b'abc\0def'), b'abc\0def')
64-
self.assertEqual(fromstringandsize(b'a'), b'a')
65-
self.assertEqual(fromstringandsize(b'a', 1), b'a')
66-
self.assertEqual(fromstringandsize(b'', 0), b'')
67-
self.assertEqual(fromstringandsize(NULL, 0), b'')
64+
65+
# Return singleton for 0 or 1 bytes
66+
self.assertIs(fromstringandsize(b'', 0), b'')
67+
self.assertIs(fromstringandsize(NULL, 0), b'')
68+
self.assertIs(fromstringandsize(b'a', 1), b'a')
69+
6870
self.assertEqual(len(fromstringandsize(NULL, 3)), 3)
6971
self.assertRaises((MemoryError, OverflowError),
7072
fromstringandsize, NULL, PY_SSIZE_T_MAX)
@@ -79,7 +81,10 @@ def test_fromstring(self):
7981
fromstring = _testlimitedcapi.bytes_fromstring
8082

8183
self.assertEqual(fromstring(b'abc\0def'), b'abc')
82-
self.assertEqual(fromstring(b''), b'')
84+
85+
# Return singleton for 0 or 1 bytes
86+
self.assertIs(fromstring(b''), b'')
87+
self.assertIs(fromstring(b'a'), b'a')
8388

8489
# CRASHES fromstring(NULL)
8590

0 commit comments

Comments
 (0)