Commit c33572a7eef for php
commit c33572a7eef54ad5abec3cf270a0d8734c0fb9ae
Author: Weilin Du <weilindu@php.net>
Date: Sun Oct 4 01:21:09 2026 +0800
ext/standard: Optimize single-character searches in strcspn() and strpbrk() (#24087)
diff --git a/UPGRADING b/UPGRADING
index 9692bfd9b2c..5fa66cfc874 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -86,6 +86,8 @@ PHP 8.7 UPGRADE NOTES
========================================
- Standard:
+ . Improved performance of strcspn() and strpbrk() when searching longer strings
+ with a single-byte character mask.
. Improved performance of array_splice() when inserting without removing
elements.
. Improved performance of str_rot13().
diff --git a/ext/standard/string.c b/ext/standard/string.c
index d23c117321a..8193b23dd8b 100644
--- a/ext/standard/string.c
+++ b/ext/standard/string.c
@@ -1740,6 +1740,11 @@ static size_t php_strspn_strcspn_common(const char *haystack, const char *charac
* We only compare in this case.
* Empirically tested that the table lookup approach is only beneficial if characters is longer than 1 character. */
if (characters_end - characters == 1) {
+ /* Avoid memchr() overhead for short spans and an immediate match. */
+ if (!must_match && haystack_end - haystack >= 16 && *haystack != *characters) {
+ const char *ptr = memchr(haystack, (unsigned char) *characters, haystack_end - haystack);
+ return ptr ? (size_t) (ptr - haystack) : (size_t) (haystack_end - haystack);
+ }
const char *ptr = haystack;
while (ptr < haystack_end && (*ptr == *characters) == must_match) {
ptr++;