Monday, June 29, 2009

Echo vs Output buffer

Here I am again. Lately i've been working on my framework - Samstyle PHP Framework - and now i am here to share with you about Echo versus Output Buffering.

Just today I have tested and proved why output buffering then echo is always better than a direct echo. For this, i created a script that will first run:

$u = 10000;
while($u-- > 0){echo 'testing 123<br/>';}

then next run the following:

$u = 10000;
$b = '';
while($u-- > 0){$b.= 'testing 123<br/>';}
echo $b;

(Psst for reasons why I used a while loop over for loop, look at: )
and then I calculated time taken to execute each of the code.

I found that buffering the output in a variable first (in this case $b) then output, is much faster compared to direct output.

For the first run, it took 0.183017015457 seconds. As for the second run, it took 0.0580809116364 seconds. That's an amazing speed improvement of more than 1/3 of the original code.

Even running only 100 times instead of 10000 times, there's still a significant difference between the speed of the 2 runs. Try that now!

Note that the timings taken are an average of 5 runs spreaded across 5 mins (i.e. 1 run per minute) for the most accurate timings. Please note that the timings may differ from computer to computer. I am using Intel QuadCore 2.4GHz, 4GB RAM, Windows XP SP3, XAMPP 1.7.1, PHP 5.2.9.

1 comment:

Sankar lp said...

I have read your blog its very attractive and impressive. I like it your blog.

PHP 7 Training in chennai | PHP 7 Training Course

PHP 7 Training in chennai | Online PHP 7 Course