Skip to content

Instantly share code, notes, and snippets.

@mattkirman
Created October 4, 2010 20:56
Show Gist options
  • Save mattkirman/610415 to your computer and use it in GitHub Desktop.
Save mattkirman/610415 to your computer and use it in GitHub Desktop.
PHP string concatenation benchmarks. Run on a MacBook (2.4GHz Core 2 Duo, 2GB RAM) with PHP 5.3.2 (cli)
<?php
$str = '';
for ($i = 0; $i < 30000; $i++) {
$str .= 'String concatenation. ';
}
/*****************************************
0.061
0.057
0.063
-----
0.06
*****************************************/
<?php
$str = '';
for ($i = 0; $i < 30000; $i++) {
$str = $str . 'String concatenation. ';
}
/*****************************************
3.333
3.348
3.354
-----
3.35
*****************************************/
<?php
$str = '';
$sArr = array();
for ($i = 0; $i < 30000; $i++) {
$sArr[] = 'String concatenation. ';
}
$str = implode($sArr);
/*****************************************
0.092
0.088
0.089
-----
0.09
*****************************************/
<?php
$str = '';
for ($i = 0; $i < 30000; $i++, $str .= 'String concatenation. ');
/*****************************************
0.063
0.062
0.066
-----
0.06
*****************************************/
<?php
$str = 'String concatenation. ';
$times = log(30000) / log(2);
for ($i = 0; $i < $times; $i++, $str .= $str);
/*****************************************
0.059
0.056
0.058
-----
0.06
This algorithm actually generates 32768 concatenations. It's not
much faster on small sets, but is ideally suited for huge numbers
of non-atomic concatenations -
~300,000 concatenations only take 0.08 seconds.
~3,000,000 concatenations take around 0.23 seconds.
*****************************************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment