diff --git a/Misc/NEWS.d/next/Library/2026-08-04-19-50-52.gh-issue-150942.B8ytes.rst b/Misc/NEWS.d/next/Library/2026-08-04-19-50-52.gh-issue-150942.B8ytes.rst new file mode 100644 index 000000000000000..bdc93872f012616 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-04-19-50-52.gh-issue-150942.B8ytes.rst @@ -0,0 +1,2 @@ +Improve the performance of :meth:`~io.IOBase.readlines` for +:class:`io.BytesIO`, particularly in free-threaded builds. diff --git a/Modules/_io/bytesio.c b/Modules/_io/bytesio.c index 7d6053d85cd9e4a..fa3778c12273ca5 100644 --- a/Modules/_io/bytesio.c +++ b/Modules/_io/bytesio.c @@ -1,5 +1,6 @@ #include "Python.h" #include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION() +#include "pycore_list.h" // _PyList_AppendTakeRef() #include "pycore_object.h" #include "pycore_pyatomic_ft_wrappers.h" #include "pycore_sysmodule.h" // _PySys_GetSizeOf() @@ -663,11 +664,9 @@ _io_BytesIO_readlines_impl(bytesio *self, PyObject *arg) line = PyBytes_FromStringAndSize(output, n); if (!line) goto on_error; - if (PyList_Append(result, line) == -1) { - Py_DECREF(line); + if (_PyList_AppendTakeRef((PyListObject *)result, line) < 0) { goto on_error; } - Py_DECREF(line); size += n; if (maxsize > 0 && size >= maxsize) break;