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
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
:c:func:`PyBytesWriter_Resize` and :c:func:`PyBytesWriter_Grow` no longer
overallocate when the first bytes/bytearray object is allocated. Only
overallocate bytes objects at next :c:func:`PyBytesWriter_Resize` and
:c:func:`PyBytesWriter_Grow` calls. Patch by Victor Stinner.
18 changes: 13 additions & 5 deletions Objects/bytesobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3755,13 +3755,15 @@ byteswriter_resize(PyBytesWriter *writer, Py_ssize_t new_size, int resize)
}

Py_ssize_t alloc = new_size;
if (resize && writer->overallocate) {
if (alloc <= (PY_SSIZE_T_MAX - alloc / OVERALLOCATE_FACTOR)) {
alloc += alloc / OVERALLOCATE_FACTOR;
if (writer->obj != NULL) {
// Overallocate the bytes object. Do not overallocate bytearray or
// if overallocation was disabled (using the private C API).
if (writer->overallocate) {
if (alloc <= (PY_SSIZE_T_MAX - alloc / OVERALLOCATE_FACTOR)) {
alloc += alloc / OVERALLOCATE_FACTOR;
}
}
}

if (writer->obj != NULL) {
if (writer->use_bytearray) {
if (PyByteArray_Resize(writer->obj, alloc)) {
#ifdef Py_DEBUG
Expand All @@ -3784,6 +3786,12 @@ byteswriter_resize(PyBytesWriter *writer, Py_ssize_t new_size, int resize)
assert(writer->obj != NULL);
}
else {
// gh-158585: Optimistic allocation strategy: don't overallocate when
// the first bytes/bytearray object is created. The bet is that the
// most common case is that a single bytes/bytearray is needed for the
// whole writer lifecycle. In that case, PyBytesWriter_Finish() doesn't
// need to truncate the bytes/bytearray object.

char *data;
if (writer->use_bytearray) {
writer->obj = PyByteArray_FromStringAndSize(NULL, alloc);
Expand Down
Loading