Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6dfe09f

Browse files
bpo-46993: Speed up bytearray creation from list and tuple (GH-31834)
1 parent 5dd7ec5 commit 6dfe09f

2 files changed

Lines changed: 28 additions & 2 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Speed up :class:`bytearray` creation from :class:`list` and :class:`tuple` by 40%. Patch by Kumar Aditya.

Objects/bytearrayobject.c

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -844,8 +844,33 @@ bytearray___init___impl(PyByteArrayObject *self, PyObject *arg,
844844
return -1;
845845
}
846846

847-
/* XXX Optimize this if the arguments is a list, tuple */
848-
847+
if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) {
848+
Py_ssize_t size = PySequence_Fast_GET_SIZE(arg);
849+
if (PyByteArray_Resize((PyObject *)self, size) < 0) {
850+
return -1;
851+
}
852+
PyObject **items = PySequence_Fast_ITEMS(arg);
853+
char *s = PyByteArray_AS_STRING(self);
854+
for (Py_ssize_t i = 0; i < size; i++) {
855+
int value;
856+
if (!PyLong_CheckExact(items[i])) {
857+
/* Resize to 0 and go through slowpath */
858+
if (Py_SIZE(self) != 0) {
859+
if (PyByteArray_Resize((PyObject *)self, 0) < 0) {
860+
return -1;
861+
}
862+
}
863+
goto slowpath;
864+
}
865+
int rc = _getbytevalue(items[i], &value);
866+
if (!rc) {
867+
return -1;
868+
}
869+
s[i] = value;
870+
}
871+
return 0;
872+
}
873+
slowpath:
849874
/* Get the iterator */
850875
it = PyObject_GetIter(arg);
851876
if (it == NULL) {

0 commit comments

Comments
 (0)