Created
March 6, 2021 07:12
-
-
Save boospot/bced6fb9aa5fadc4203128c1d2117f85 to your computer and use it in GitHub Desktop.
Simple Benchmark to see performance of string concatenation, sprintf, strtr, and 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
$iterations = 1000000; | |
$name = 'Tom'; | |
$date = '13/09/2009'; | |
$t1 = microtime( true ); | |
for ( $i = 0; $i < $iterations; $i ++ ) { | |
$str = sprintf( 'Hi %s, you last logged in on %s.', $name, $date ); | |
} | |
$t2 = microtime( true ); | |
echo 'sprintf: ' . ( $t2 - $t1 ); | |
echo '<br />'; | |
$t1 = microtime( true ); | |
for ( $i = 0; $i < $iterations; $i ++ ) { | |
$str = 'Hi ' . $name . ', you last logged in on ' . $date; | |
} | |
$t2 = microtime( true ); | |
echo 'concat: ' . ( $t2 - $t1 ); | |
echo '<br />'; | |
$t1 = microtime( true ); | |
for ( $i = 0; $i < $iterations; $i ++ ) { | |
$str = strtr( 'Hi %name, you last logged in on %date.', array( | |
'%name' => $name, | |
'%date' => $date | |
) ); | |
} | |
$t2 = microtime( true ); | |
echo 'strtr: ' . ( $t2 - $t1 ); | |
echo '<br />'; | |
$t1 = microtime( true ); | |
for ( $i = 0; $i < $iterations; $i ++ ) { | |
$str = 'Hi %name, you last logged in on %date.'; | |
str_replace('%name', $name, $str); | |
str_replace('%date', $date, $str); | |
} | |
$t2 = microtime( true ); | |
echo 'str_replace: ' . ( $t2 - $t1 ); | |
echo '<br />'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment