Created
November 30, 2018 08:52
-
-
Save viperet/d049cb669b874b3a59b42721fec0d6ed to your computer and use it in GitHub Desktop.
PHP string concatenation benchmark
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 | |
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