Skip to content

bpo-46993: Speed up bytearray creation from list and tuple #31834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Mar 15, 2022
Merged
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 @@
Speed up :class:`bytearray` creation from :class:`list` and :class:`tuple` by 40%. Patch by Kumar Aditya.
29 changes: 27 additions & 2 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -844,8 +844,33 @@ bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
return -1;
}

/* XXX Optimize this if the arguments is a list, tuple */

if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) {
Py_ssize_t size = PySequence_Fast_GET_SIZE(arg);
if (PyByteArray_Resize((PyObject *)self, size) < 0) {
return -1;
}
PyObject **items = PySequence_Fast_ITEMS(arg);
char *s = PyByteArray_AS_STRING(self);
for (Py_ssize_t i = 0; i < size; i++) {
int value;
if (!PyLong_CheckExact(items[i])) {
/* Resize to 0 and go through slowpath */
if (Py_SIZE(self) != 0) {
if (PyByteArray_Resize((PyObject *)self, 0) < 0) {
return -1;
}
}
goto slowpath;
}
int rc = _getbytevalue(items[i], &value);
if (!rc) {
return -1;
}
s[i] = value;
}
return 0;
}
slowpath:
/* Get the iterator */
it = PyObject_GetIter(arg);
if (it == NULL) {
Expand Down