Skip to content

Instantly share code, notes, and snippets.

@viperet
Created November 30, 2018 08:52
Show Gist options
  • Save viperet/d049cb669b874b3a59b42721fec0d6ed to your computer and use it in GitHub Desktop.
Save viperet/d049cb669b874b3a59b42721fec0d6ed to your computer and use it in GitHub Desktop.
PHP string concatenation benchmark
<?php
function starttime() {
$r = explode( ' ', microtime() );
$r = $r[1] + $r[0];
return $r;
}
function endtime($starttime) {
$r = explode( ' ', microtime() );
$r = $r[1] + $r[0];
$r = round($r - $starttime,4);
return '<strong>Execution Time</strong>: '.$r.' seconds<br />';
}
$times = 100000;
$start = starttime();
$s = ''; $p = 'asdfghjkl';
for($i=0;$i<$times;$i++) {
$s = $s . '<p>' . $p . '</p>';
}
echo 'String length '.strlen($s).'<br>';
echo 'Concatenation using dot operator ' . endtime($start);
$start = starttime();
$s = ''; $p = 'asdfghjkl';
for($i=0;$i<$times;$i++) {
$s = "{$s}<p>{$p}</p>";
}
echo 'String length '.strlen($s).'<br>';
echo 'Concatenation using variable expansion ' . endtime($start);
$start = starttime();
$s = ''; $p = 'asdfghjkl';
ob_start();
for($i=0;$i<$times;$i++) {
?><p><?=$p?></p><?php
}
$s = ob_get_clean();
echo 'String length '.strlen($s).'<br>';
echo 'Concatenation using output buffering ' . endtime($start);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment