gh-139871: Optimize bytearray construction with encoding (#142243) · python/cpython@14e6052 · GitHub
Skip to content

Commit 14e6052

Browse files
authored
gh-139871: Optimize bytearray construction with encoding (#142243)
When a `str` is encoded in `bytearray.__init__` the encoder tends to create a new unique bytes object. Rather than allocate new memory and copy the bytes use the already created bytes object as bytearray backing. The bigger the `str` the bigger the saving. Mean +- std dev: [main_encoding] 497 us +- 9 us -> [encoding] 14.2 us +- 0.3 us: 34.97x faster ```python import pyperf runner = pyperf.Runner() runner.timeit( name="encode", setup="a = 'a' * 1_000_000", stmt="bytearray(a, encoding='utf8')") ```
1 parent 850f95f commit 14e6052

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

Objects/bytearrayobject.c

Lines changed: 16 additions & 1 deletion

0 commit comments

Comments
 (0)