echo vs. assignment and string concatenation inside a display function.
I made this function nav() to display the navigation
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 '
';
}
function nav2() {
global $pgs;
$html = '
';
echo $html;
}
/* The Test */
$t = microtime(true);
for($i = 0; $i < 100; ++$i) {
nav();
}
echo '';
echo ($t = (microtime(true) - $t));
for($i = 0; $i < 100; ++$i) {
nav2();
}
echo '';
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.)