|
| 1 | +<?php |
| 2 | + |
| 3 | +function benchmark($name, $func) { |
| 4 | + $start = microtime(true); |
| 5 | + // A lower iteration count because str_ireplace can be very slow with arrays on long strings. |
| 6 | + for ($i = 0; $i < 500; $i++) { |
| 7 | + $func(); |
| 8 | + } |
| 9 | + $end = microtime(true); |
| 10 | + echo str_pad($name, 50) . ": " . number_format($end - $start, 6) . "s\n"; |
| 11 | +} |
| 12 | + |
| 13 | +echo "Benchmarking current str_ireplace implementation...\n"; |
| 14 | + |
| 15 | +// A long string (~22KB) with a variety of characters to search for. |
| 16 | +$long_haystack = str_repeat("The quick brown fox jumps over the lazy dog. ", 500); |
| 17 | + |
| 18 | +// An array of search terms that will all be found. |
| 19 | +$search_array = ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'lazy', 'dog']; |
| 20 | +$replace_array = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']; |
| 21 | + |
| 22 | +// An array of search terms that will not be found. |
| 23 | +$search_array_no_match = ['xylophone', 'yak', 'zebra', 'walrus', 'vulture', 'unicorn', 'tiger', 'snake']; |
| 24 | + |
| 25 | +// ===== TEST CASES ===== |
| 26 | + |
| 27 | +// Case 1: Simple string search (no arrays) for baseline comparison. |
| 28 | +benchmark("Simple string search", function() use ($long_haystack) { |
| 29 | + str_ireplace('fox', 'cat', $long_haystack); |
| 30 | +}); |
| 31 | + |
| 32 | +// Case 2: Array search, single replace. THIS IS THE PRIMARY OPTIMIZATION TARGET. |
| 33 | +benchmark("Array search, single replacement", function() use ($long_haystack, $search_array) { |
| 34 | + str_ireplace($search_array, 'REPLACED', $long_haystack); |
| 35 | +}); |
| 36 | + |
| 37 | +// Case 3: Array search, array replace. THIS IS THE PRIMARY OPTIMIZATION TARGET. |
| 38 | +benchmark("Array search, array replacement", function() use ($long_haystack, $search_array, $replace_array) { |
| 39 | + str_ireplace($search_array, $replace_array, $long_haystack); |
| 40 | +}); |
| 41 | + |
| 42 | +// Case 4: Array search with no matches. To ensure no performance regression. |
| 43 | +benchmark("Array search, no matches", function() use ($long_haystack, $search_array_no_match) { |
| 44 | + str_ireplace($search_array_no_match, 'REPLACED', $long_haystack); |
| 45 | +}); |
| 46 | + |
| 47 | +?> |
0 commit comments