[php-src] master: ext/standard: Optimize single-character searches in strcspn() and strpbrk() (#24087)

From: Date: Sat, 03 Oct 2026 17:21:12 +0000
Subject: [php-src] master: ext/standard: Optimize single-character searches in strcspn() and strpbrk() (#24087)
Groups: php.cvs 
Request: Send a blank email to php-cvs+get-141907@lists.php.net to get a copy of this message
Author: Weilin Du (LamentXU123) Committer: GitHub (web-flow) Pusher: LamentXU123 Date: 2026-10-04T01:21:09+08:00 Commit: https://github.com/php/php-src/commit/c33572a7eef54ad5abec3cf270a0d8734c0fb9ae Raw diff: https://github.com/php/php-src/commit/c33572a7eef54ad5abec3cf270a0d8734c0fb9ae.diff ext/standard: Optimize single-character searches in strcspn() and strpbrk() (#24087) Changed paths: M UPGRADING M ext/standard/string.c Diff: diff --git a/UPGRADING b/UPGRADING index 9692bfd9b2cc..5fa66cfc8749 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 d23c117321a4..8193b23dd8bc 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++;

« previous php.cvs (#141907) next »