Skip to content

Commit ca28691

Browse files
committed
Optimize unicode string comparison with early length check
1 parent 2cd24eb commit ca28691

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

Objects/unicodeobject.c

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11200,12 +11200,17 @@ unicode_compare(PyObject *str1, PyObject *str2)
1120011200
const void *data1, *data2;
1120111201
Py_ssize_t len1, len2, len;
1120211202

11203+
// Fast path: if lengths are different, we can return immediately
11204+
len1 = PyUnicode_GET_LENGTH(str1);
11205+
len2 = PyUnicode_GET_LENGTH(str2);
11206+
if (len1 != len2) {
11207+
return (len1 < len2) ? -1 : 1;
11208+
}
11209+
1120311210
kind1 = PyUnicode_KIND(str1);
1120411211
kind2 = PyUnicode_KIND(str2);
1120511212
data1 = PyUnicode_DATA(str1);
1120611213
data2 = PyUnicode_DATA(str2);
11207-
len1 = PyUnicode_GET_LENGTH(str1);
11208-
len2 = PyUnicode_GET_LENGTH(str2);
1120911214
len = Py_MIN(len1, len2);
1121011215

1121111216
switch(kind1) {

0 commit comments

Comments
 (0)