Skip to content

Instantly share code, notes, and snippets.

@KVytyagov
Last active July 11, 2024 11:47
Show Gist options
  • Select an option

  • Save KVytyagov/25bc59ea7fa543b0ef9989a8d23e3a04 to your computer and use it in GitHub Desktop.

Select an option

Save KVytyagov/25bc59ea7fa543b0ef9989a8d23e3a04 to your computer and use it in GitHub Desktop.
Performance test strtr vs str_replace
<?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";
@vlakoff
Copy link

vlakoff commented Jul 11, 2024

The "Strtr 3 arguments" use is incorrect. See documentation:

If given three arguments, this function returns a copy of string where all occurrences of each (single-byte) character in from have been translated to the corresponding character in to, i.e., every occurrence of $from[$n] has been replaced with $to[$n], where $n is a valid offset in both arguments.

Maybe an example would help understand better: strtr('baab', 'ab', '01') returns 1001.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment