Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boospot/bced6fb9aa5fadc4203128c1d2117f85 to your computer and use it in GitHub Desktop.
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
$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