[php-src] PR #25851: ext/standard: Avoid redundant searches in str_replace()

From: Date: Fri, 27 Nov 2026 18:52:30 +0000
Subject: [php-src] PR #25851: ext/standard: Avoid redundant searches in str_replace()
Groups: php.git-pulls 
Request: Send a blank email to git-pulls+get-41137@lists.php.net to get a copy of this message
Pull Request: https://github.com/php/php-src/pull/25851 Author: LamentXU123 When the search string is longer than one byte and its replacement has a different length, str_replace() counts matches before allocating the result. Two things: - We can reuse the first match from that pass - We can stop searching once all counted matches have been copied. Err, so now when the search string occurs once, the copy pass performs no substring searches. It is really very interesting to do these optimizations :) ``` <?php $half = str_repeat('a', 2044); $subject = $half . '{{name}}' . $half; $start = hrtime(true); for ($i = 0; $i < 1_000_000; ++$i) { $result = str_replace('{{name}}', 'Alice', $subject); } printf("%.1f ms\n", (hrtime(true) - $start) / 1e6); ``` Before the call average use 139.0 ms, after this it use **only 96.1 ms** roughly 30.86% increasement. Also this can cause some reducsion in memory comsumpty as well.

« previous php.git-pulls (#41137) next »