[php-src] PR #19272: Optimize performances of `str_pad()`

From: Date: Mon, 28 Jul 2025 09:11:26 +0000
Subject: [php-src] PR #19272: Optimize performances of `str_pad()`
Groups: php.git-pulls 
Request: Send a blank email to git-pulls+get-32643@lists.php.net to get a copy of this message
Pull Request: https://github.com/php/php-src/pull/19272 Author: alexandre-daubois I would like to propose this optimization for str_pad(). Here is the benchmark code: <details> <summary>Benchmark code</summary> ```php <?php function run_benchmark_round($round) { echo "=== Round $round ===\n"; $iterations = 1000000; $test_cases = [ 'single_char_50' => ['hello', 50, ' ', STR_PAD_RIGHT], 'single_char_200' => ['test', 200, '0', STR_PAD_LEFT], 'single_char_1000' => ['data', 1000, '*', STR_PAD_BOTH], 'multi_char_50' => ['hello', 50, '=-', STR_PAD_RIGHT], 'multi_char_200' => ['test', 200, 'ABC', STR_PAD_LEFT], 'multi_char_1000' => ['data', 1000, '***', STR_PAD_BOTH], ]; $results = []; foreach ($test_cases as $name => [$str, $len, $pad, $type]) { for ($i = 0; $i < 5000; $i++) { str_pad($str, $len, $pad, $type); } $start = hrtime(true); for ($i = 0; $i < $iterations; $i++) { str_pad($str, $len, $pad, $type); } $end = hrtime(true); $nanoseconds = $end - $start; $milliseconds = $nanoseconds / 1e6; $results[$name] = $milliseconds; echo sprintf("%-20s: %8.2f ms\n", $name, $milliseconds); } echo "\n"; return $results; } function calculate_stats($all_results) { $test_names = array_keys($all_results[0]); foreach ($test_names as $test) { $times = []; foreach ($all_results as $round_results) { $times[] = $round_results[$test]; } $avg = array_sum($times) / count($times); $min = min($times); $max = max($times); echo sprintf("%-20s: avg=%7.2f ms min=%7.2f ms max=%7.2f ms\n", $test, $avg, $min, $max); } } echo "Iterations per test: 1,000,000\n"; $all_results = []; for ($round = 1; $round <= 5; $round++) { $all_results[] = run_benchmark_round($round); } calculate_stats($all_results); ``` </details> The results are the following for 1 million iterations: ``` Master ====== single_char_50 : avg= 95.36 ms min= 93.07 ms max= 101.31 ms single_char_200 : avg= 121.09 ms min= 119.66 ms max= 124.02 ms single_char_1000 : avg=1304.33 ms min=1206.17 ms max=1359.98 ms multi_char_50 : avg= 90.42 ms min= 89.19 ms max= 91.54 ms multi_char_200 : avg= 123.73 ms min= 121.70 ms max= 130.18 ms multi_char_1000 : avg=1251.82 ms min=1015.81 ms max=1400.16 ms Branch ====== single_char_50 : avg= 31.82 ms min= 29.01 ms max= 41.34 ms single_char_200 : avg= 27.47 ms min= 26.91 ms max= 28.26 ms single_char_1000 : avg= 33.87 ms min= 33.35 ms max= 35.39 ms multi_char_50 : avg= 65.00 ms min= 63.76 ms max= 66.79 ms multi_char_200 : avg= 142.84 ms min= 141.77 ms max= 143.65 ms multi_char_1000 : avg= 601.21 ms min= 599.11 ms max= 603.21 ms ``` The idea is to avoid modulo operation in loops and copying char by char. Instead, this PR prefers the bulk copy approach.

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