Optimize bytearray % args · wrongnull/cpython@772b2b0 · GitHub
Skip to content

Commit 772b2b0

Browse files
committed
Optimize bytearray % args
Issue python#25399: Don't create temporary bytes objects: modify _PyBytes_Format() to create work directly on bytearray objects. * Rename _PyBytes_Format() to _PyBytes_FormatEx() just in case if something outside CPython uses it * _PyBytes_FormatEx() now uses (char*, Py_ssize_t) for the input string, so bytearray_format() doesn't need tot create a temporary input bytes object * Add use_bytearray parameter to _PyBytes_FormatEx() which is passed to _PyBytesWriter, to create a bytearray buffer instead of a bytes buffer Most formatting operations are now between 2.5 and 5 times faster.
1 parent 661aacc commit 772b2b0

3 files changed

Lines changed: 33 additions & 36 deletions

File tree

Include/bytesobject.h

Lines changed: 5 additions & 1 deletion

Objects/bytearrayobject.c

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -282,26 +282,14 @@ PyByteArray_Concat(PyObject *a, PyObject *b)
282282
static PyObject *
283283
bytearray_format(PyByteArrayObject *self, PyObject *args)
284284
{
285-
PyObject *bytes_in, *bytes_out, *res;
286-
char *bytestring;
287-
288-
if (self == NULL || !PyByteArray_Check(self) || args == NULL) {
285+
if (self == NULL || !PyByteArray_Check(self)) {
289286
PyErr_BadInternalCall();
290287
return NULL;
291288
}
292-
bytestring = PyByteArray_AS_STRING(self);
293-
bytes_in = PyBytes_FromString(bytestring);
294-
if (bytes_in == NULL)
295-
return NULL;
296-
bytes_out = _PyBytes_Format(bytes_in, args);
297-
Py_DECREF(bytes_in);
298-
if (bytes_out == NULL)
299-
return NULL;
300-
res = PyByteArray_FromObject(bytes_out);
301-
Py_DECREF(bytes_out);
302-
if (res == NULL)
303-
return NULL;
304-
return res;
289+
290+
return _PyBytes_FormatEx(PyByteArray_AS_STRING(self),
291+
PyByteArray_GET_SIZE(self),
292+
args, 1);
305293
}
306294

307295
/* Functions stuffed into the type object */

Objects/bytesobject.c

Lines changed: 23 additions & 18 deletions

0 commit comments

Comments
 (0)