Skip to content

bpo-47005: Improve performance of bytearray_repeat and bytearray_irepeat #31856

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 3 commits into from
Mar 17, 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 @@
Improve performance of ``bytearray_repeat`` and ``bytearray_irepeat`` by reducing the number of invocations of ``memcpy``.
28 changes: 22 additions & 6 deletions Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,19 @@ bytearray_repeat(PyByteArrayObject *self, Py_ssize_t count)
if (mysize == 1)
memset(result->ob_bytes, buf[0], size);
else {
Py_ssize_t i;
for (i = 0; i < count; i++)
memcpy(result->ob_bytes + i*mysize, buf, mysize);
Py_ssize_t i, j;

i = 0;
if (i < size) {
memcpy(result->ob_bytes, buf, mysize);
i = mysize;
}
// repeatedly double the number of bytes copied
while (i < size) {
j = Py_MIN(i, size - i);
memcpy(result->ob_bytes + i, result->ob_bytes, j);
i += j;
}
}
}
return (PyObject *)result;
Expand All @@ -363,9 +373,15 @@ bytearray_irepeat(PyByteArrayObject *self, Py_ssize_t count)
if (mysize == 1)
memset(buf, buf[0], size);
else {
Py_ssize_t i;
for (i = 1; i < count; i++)
memcpy(buf + i*mysize, buf, mysize);
Py_ssize_t i, j;

i = mysize;
// repeatedly double the number of bytes copied
while (i < size) {
j = Py_MIN(i, size - i);
memcpy(buf + i, buf, j);
i += j;
}
}

Py_INCREF(self);
Expand Down