Posted:
echo vs. assignment and string concatenation inside a display function.
I made this function nav() to display the navigation <ul> (unordered list) on index.php for my main page because I wanted to reuse this code on index.php of my wordpress blog for the same site. two index.php pages... i couldn't figure out how to condence the wp index.php file into my main index.php file for the main part of the site...
anyway... i did a benchmark test between nav() and nav2(), which uses a slightly different approach than nav(). I saw nav2's approach used in facebook's code for sample facebook apps (like smiley, and therunaround)... but it looked slower than nav() because it creates an unnecessary (in my opinion) variable ($html) and assigns to it multiple times, (and I think assignments take longer than one cycle).
I did a benchmark test to test my hypothesis.
<?php
// filename: display.inc
// this file gets included in index.php, with include(), and I ran it by loading index.php.
/*
* Render the main navigation that goes at the top of each page.
*/
function nav() {
global $pgs;
echo '<ul id="nav">';
foreach($pgs as $pg_key => $pg) {
$pg_pname = $pg['pname'] ? $pg['pname'] : $pg_key;
$pg_aname = $pg['aname'] ? $pg['aname'] : ucfirst($pg_pname);
$pg_link = is_null($pg['link']) ? $pg_key : $pg['link'];
echo '<li class="',$pg_pname,'"><a href="',BASE_PATH,$pg_link,'">',$pg_aname,'</a></li>';
}
echo '</ul>';
}
function nav2() {
global $pgs;
$html = '<ul id="nav">';
foreach($pgs as $pg_key => $pg) {
$pg_pname = $pg['pname'] ? $pg['pname'] : $pg_key;
$pg_aname = $pg['aname'] ? $pg['aname'] : ucfirst($pg_pname);
$pg_link = is_null($pg['link']) ? $pg_key : $pg['link'];
$html .= '<li class="'.$pg_pname.'"><a href="'.BASE_PATH.$pg_link.'">'.$pg_aname.'</a></li>';
}
$html .= '</ul>';
echo $html;
}
/* The Test */
$t = microtime(true);
for($i = 0; $i < 100; ++$i) {
nav();
}
echo '<br>';
echo ($t = (microtime(true) - $t));
for($i = 0; $i < 100; ++$i) {
nav2();
}
echo '<br>';
echo ($t = (microtime(true) - $t));
Results:
nav() took 0.0039050579071 ms to run 100 times
nav2() took 1242865035.99 ms to run 100 times
Discussion:
nav() runs much faster than nav2().
Conclusion:
Use nav() style. i.e. when feasible, replace string concatenations and string variable assignments with echo() (separating arguments with commas).
No wonder facebook is so slow... :P (I kiddd... I love facebook. I'm sure they have some really smart people working there.)