]> git.ipfire.org Git - thirdparty/Python/cpython.git/commit
gh-139871: Optimize bytearray construction with encoding (#142243)
authorCody Maloney <cmaloney@users.noreply.github.com>
Mon, 15 Dec 2025 12:10:31 +0000 (04:10 -0800)
committerGitHub <noreply@github.com>
Mon, 15 Dec 2025 12:10:31 +0000 (13:10 +0100)
commit14e6052b438d99acaba7a39d454af98cfdf5cac7
tree503de1293a162dc41243dcd77a5a458aefb76026
parent850f95f6f64a55920cbb91b022b70b736bd20ed8
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')")
```
Objects/bytearrayobject.c