Skip to content

Commit d301587

Browse files
authored
pythongh-140135: Use PyBytesWriter in io.RawIOBase.readall(); 4x faster (python#140139)
1 parent 0c66da8 commit d301587

File tree

2 files changed

+16
-16
lines changed

2 files changed

+16
-16
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up :meth:`io.RawIOBase.readall` by using PyBytesWriter API (about 4x
2+
faster)

Modules/_io/iobase.c

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -962,12 +962,10 @@ static PyObject *
962962
_io__RawIOBase_readall_impl(PyObject *self)
963963
/*[clinic end generated code: output=1987b9ce929425a0 input=688874141213622a]*/
964964
{
965-
int r;
966-
PyObject *chunks = PyList_New(0);
967-
PyObject *result;
968-
969-
if (chunks == NULL)
965+
PyBytesWriter *writer = PyBytesWriter_Create(0);
966+
if (writer == NULL) {
970967
return NULL;
968+
}
971969

972970
while (1) {
973971
PyObject *data = _PyObject_CallMethod(self, &_Py_ID(read),
@@ -978,38 +976,38 @@ _io__RawIOBase_readall_impl(PyObject *self)
978976
if (_PyIO_trap_eintr()) {
979977
continue;
980978
}
981-
Py_DECREF(chunks);
979+
PyBytesWriter_Discard(writer);
982980
return NULL;
983981
}
984982
if (data == Py_None) {
985-
if (PyList_GET_SIZE(chunks) == 0) {
986-
Py_DECREF(chunks);
983+
if (PyBytesWriter_GetSize(writer) == 0) {
984+
PyBytesWriter_Discard(writer);
987985
return data;
988986
}
989987
Py_DECREF(data);
990988
break;
991989
}
992990
if (!PyBytes_Check(data)) {
993-
Py_DECREF(chunks);
994991
Py_DECREF(data);
995992
PyErr_SetString(PyExc_TypeError, "read() should return bytes");
993+
PyBytesWriter_Discard(writer);
996994
return NULL;
997995
}
998996
if (PyBytes_GET_SIZE(data) == 0) {
999997
/* EOF */
1000998
Py_DECREF(data);
1001999
break;
10021000
}
1003-
r = PyList_Append(chunks, data);
1004-
Py_DECREF(data);
1005-
if (r < 0) {
1006-
Py_DECREF(chunks);
1001+
if (PyBytesWriter_WriteBytes(writer,
1002+
PyBytes_AS_STRING(data),
1003+
PyBytes_GET_SIZE(data)) < 0) {
1004+
Py_DECREF(data);
1005+
PyBytesWriter_Discard(writer);
10071006
return NULL;
10081007
}
1008+
Py_DECREF(data);
10091009
}
1010-
result = PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), chunks);
1011-
Py_DECREF(chunks);
1012-
return result;
1010+
return PyBytesWriter_Finish(writer);
10131011
}
10141012

10151013
static PyObject *

0 commit comments

Comments
 (0)