Skip to content

Commit 423fd33

Browse files
authored
ext/standard: Avoid redundant searches in str_replace() (#25851)
Reuse the first match from the counting pass and stop copying matches at the last known match end. When all matches are adjacent, advance directly to the next match.
1 parent 45a58ad commit 423fd33

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

‎UPGRADING‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,8 @@ PHP 8.7 UPGRADE NOTES
247247
. Improved performance of array_chunk() when not preserving keys.
248248
. Improved performance of array_splice() when inserting without removing
249249
elements.
250+
. Improved performance of str_replace() when the search string is longer than
251+
one byte and the replacement has a different length.
250252
. Improved performance of str_rot13().
251253
. Improved performance of pack() for large strings using the a, A and Z
252254
formats.

‎ext/standard/string.c‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3337,12 +3337,12 @@ static zend_string *php_str_to_str_ex(zend_string *haystack,
33373337
return new_str;
33383338
} else {
33393339
size_t count = 0;
3340-
const char *o = ZSTR_VAL(haystack);
3341-
const char *n = needle;
3342-
const char *endp = o + ZSTR_LEN(haystack);
3340+
const char *last_match_end = ZSTR_VAL(haystack);
3341+
end = last_match_end + ZSTR_LEN(haystack);
3342+
const char *first_match = php_memnstr(last_match_end, needle, needle_len, end);
33433343

3344-
while ((o = (char*)php_memnstr(o, n, needle_len, endp))) {
3345-
o += needle_len;
3344+
for (r = first_match; r; r = php_memnstr(last_match_end, needle, needle_len, end)) {
3345+
last_match_end = r + needle_len;
33463346
count++;
33473347
}
33483348
if (count == 0) {
@@ -3359,11 +3359,17 @@ static zend_string *php_str_to_str_ex(zend_string *haystack,
33593359
}
33603360

33613361
e = ZSTR_VAL(new_str);
3362-
end = ZSTR_VAL(haystack) + ZSTR_LEN(haystack);
3363-
for (p = ZSTR_VAL(haystack); (r = (char*)php_memnstr(p, needle, needle_len, end)); p = r + needle_len) {
3362+
*replace_count += count;
3363+
p = ZSTR_VAL(haystack);
3364+
/* If all matches are adjacent, their positions are already known. */
3365+
bool adjacent = first_match + count * needle_len == last_match_end;
3366+
for (r = first_match; ; r = adjacent ? p : php_memnstr(p, needle, needle_len, end)) {
33643367
e = zend_mempcpy(e, p, r - p);
33653368
e = zend_mempcpy(e, str, str_len);
3366-
(*replace_count)++;
3369+
p = r + needle_len;
3370+
if (p == last_match_end) {
3371+
break;
3372+
}
33673373
}
33683374

33693375
if (p < end) {

0 commit comments

Comments
 (0)