Fix: PHP “echo()” function performance

Few days back, i was optimizing performance of a website. After all benchmark probes placed … i detected that the echo() statement is taking almost 1.6s just to print the $string variable of size around 100K. It sound very pathetic when all your DB fetching and other things are under 0.1s and echo() is taking 1.6s. It reminded me about the website (that log the big issues of php) shared by my colleague (kadnan) few days back

Actual problem …

$t1 = microtime(true);
echo $html;
$t2 = microtime(true);
echo ($t2-$t1);

I researched on web, and found that it is a known issue with PHP’s Nagle’s Algorithm that is used in echo function.

I alternatively used print() but still it decreased to 1.1s but still not that i want.

A solution was proposed, to split the string in small pieces and then echo … it improved till 1s, but still not that i want.

function echobig($string, $bufferSize = 8192) {
$splitString = str_split($string, $bufferSize);
foreach($splitString as $chunk) {
echo $chunk;

Promising Solution

i got this comment from a blog …

Guys, I think I narrowed it down even further!

As previously said, PHP buffering will let PHP race to the end of your script, but after than it will still “hang” while trying to pass all that data to Apache.

Now I was able, not only to measure this (see previous comment) but to actually eliminate the waiting period inside of PHP. I did that by increasing Apache’s SendBuffer with the SendBufferSize directive.

This pushes the data out of PHP faster. I guess the next step would be to get it out of Apache faster but I’m not sure if there is actually another configurable layer between Apache and the raw network bandwidth.

– Francois Planque

This seems very promising, as peoples commented … and i’ll be going to try it very soon.