[php-src] master: ext/standard: Optimize str_pad() using doubling copies (#23661)
| From: | Weilin Du via GitHub | Date: | Sat, 12 Sep 2026 05:28:06 +0000 |
| Subject: | [php-src] master: ext/standard: Optimize str_pad() using doubling copies (#23661) | ||
| Groups: | php.cvs | ||
| Request: | Send a blank email to php-cvs+get-141171@lists.php.net to get a copy of this message | ||
Author: Weilin Du (LamentXU123)
Committer: GitHub (web-flow)
Pusher: LamentXU123
Date: 2026-09-12T13:28:03+08:00
Commit: https://github.com/php/php-src/commit/74e3a69df1a5e86b1874ec562831ed4db58f7a38
Raw diff: https://github.com/php/php-src/commit/74e3a69df1a5e86b1874ec562831ed4db58f7a38.diff
ext/standard: Optimize str_pad() using doubling copies (#23661)
This PR optimizes the user-visible
str_pad() by reducing repeated small
copy operations during padding. In php_str_pad_fill(), the algorithm now uses
doubling copies to grow the written region exponentially. This lowers memcpy counts
and improves throughput for large repeated-pattern padding workloads.
Added str_pad_repeated_pattern.phpt to validate repeated pattern and partial-tail
boundaries, including multi-byte patterns and all pad directions. Behavior is
unchanged; this is a performance-only change and is now recorded in the PHP 8.6
performance changelog.
Changed paths:
M UPGRADING
M ext/standard/string.c
Diff:
diff --git a/UPGRADING b/UPGRADING
index a866bc223e42..3980faa4294d 100644
--- a/UPGRADING
+++ b/UPGRADING
@@ -1105,6 +1105,7 @@ PHP 8.6 UPGRADE NOTES
. Improved performance of array_walk().
. Improved performance of intval('+0b...', 2) and intval('0b...', 2).
. Improved performance of str_split().
+ . Improved performance of str_pad().
- URI:
. Improved performance of Uri\WhatWg\Url::parse() when collecting
diff --git a/ext/standard/string.c b/ext/standard/string.c
index 04c3c21b2866..577d4267ed2f 100644
--- a/ext/standard/string.c
+++ b/ext/standard/string.c
@@ -5891,13 +5891,15 @@ static void php_str_pad_fill(zend_string *result, size_t pad_chars, const
char *
return;
}
+ const char *start = p;
const char *end = p + pad_chars;
- while (p + pad_str_len <= end) {
- p = zend_mempcpy(p, pad_str, pad_str_len);
- }
+ size_t len = MIN(pad_str_len, pad_chars);
+ p = zend_mempcpy(p, pad_str, len);
- if (p < end) {
- memcpy(p, pad_str, end - p);
+ /* Double the filled area on each iteration. */
+ while (p < end) {
+ len = MIN(p - start, end - p);
+ p = zend_mempcpy(p, start, len);
}
ZSTR_LEN(result) += pad_chars;