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"; |
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 infrom
have been translated to the corresponding character into
, 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
PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Apr 5 2018 08:53:57) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.2.4-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
Str_Replace scalars: 0.69700789451599
Str_Replace search array, replace scalar: 1.101686000824
Str_Replace search array, replace array: 1.4618530273438
Strtr 3 arguments: 1.987979888916
Strtr 2 arguments: 1.0328650474548