8000 gh-117431: Improve performance of startswith and endswith by eendebakpt · Pull Request #117782 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-117431: Improve performance of startswith and endswith #117782

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

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
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 :meth:`str.startswith`, :meth:`str.endswith`, :meth:`str.removeprefix` and :meth:`str.removesuffix`.
23 changes: 10 additions & 13 deletions Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -9943,24 +9943,21 @@ tailmatch(PyObject *self,
else
offset = start;

if (PyUnicode_READ(kind_self, data_self, offset) ==
PyUnicode_READ(kind_sub, data_sub, 0) &&
PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
PyUnicode_READ(kind_sub, data_sub, end_sub)) {
int match_last = PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
PyUnicode_READ(kind_sub, data_sub, end_sub);

if (match_last) {
/* If both are of the same kind, memcmp is sufficient */
if (kind_self == kind_sub) {
return ! memcmp((char *)data_self +
(offset * PyUnicode_KIND(substring)),
data_sub,
PyUnicode_GET_LENGTH(substring) *
PyUnicode_KIND(substring));
return ! memcmp((char *)data_self + (offset * kind_sub),
data_sub, end_sub * kind_sub);
}
/* otherwise we have to compare each character by first accessing it */
else {
/* We do not need to compare 0 and len(substring)-1 because
the if statement above ensured already that they are equal
when we end up here. */
for (i = 1; i < end_sub; ++i) {
/* We do not need to compare len(substring)-1 because the check on
match_last above ensured already that they are equal when we
end up here. */
for (i = 0; i < end_sub; ++i) {
if (PyUnicode_READ(kind_self, data_self, offset + i) !=
PyUnicode_READ(kind_sub, data_sub, i))
return 0;
Expand Down
Loading
0