Last active
July 11, 2024 11:47
-
-
Save KVytyagov/25bc59ea7fa543b0ef9989a8d23e3a04 to your computer and use it in GitHub Desktop.
Performance test strtr vs str_replace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| $iterations = 10000000; | |
| $defaultString = 'Test string m8'; | |
| $replaceTpl = 'm8'; | |
| $placeholder = 'is more effective'; | |
| $start = microtime(true); | |
| for ($i = 0; $i < $iterations; ++$i) { | |
| $out = str_replace($replaceTpl, $placeholder, $defaultString); | |
| } | |
| $time = microtime(true) - $start; | |
| echo 'Str_Replace scalars: ' . $time . "\n"; | |
| $start = microtime(true); | |
| for ($i = 0; $i < $iterations; ++$i) { | |
| $out = str_replace([$replaceTpl], $placeholder, $defaultString); | |
| } | |
| $time = microtime(true) - $start; | |
| echo 'Str_Replace search array, replace scalar: ' . $time . "\n"; | |
| $start = microtime(true); | |
| for ($i = 0; $i < $iterations; ++$i) { | |
| $out = str_replace([$replaceTpl], [$placeholder], $defaultString); | |
| } | |
| $time = microtime(true) - $start; | |
| echo 'Str_Replace search array, replace array: ' . $time . "\n"; | |
| $start = microtime(true); | |
| for ($i = 0; $i < $iterations; ++$i) { | |
| $out = strtr($defaultString, $replaceTpl, $placeholder); | |
| } | |
| $time = microtime(true) - $start; | |
| echo 'Strtr 3 arguments: ' . $time . "\n"; | |
| $start = microtime(true); | |
| for ($i = 0; $i < $iterations; ++$i) { | |
| $out = strtr($defaultString, [$replaceTpl => $placeholder]); | |
| } | |
| $time = microtime(true) - $start; | |
| echo 'Strtr 2 arguments: ' . $time . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The "Strtr 3 arguments" use is incorrect. See documentation:
Maybe an example would help understand better:
strtr('baab', 'ab', '01')returns 1001.