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 phpsadness.com (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.

http://www.php.net/manual/en/function.echo.php#52881

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 …
http://wonko.com/post/seeing_poor_performance_using_phps_echo_statement_heres_why#comment-5607

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.

Reference:
http://wonko.com/post/seeing_poor_performance_using_phps_echo_statement_heres_why
http://phplens.com/lens/php-book/optimizing-debugging-php.php
http://www.php.net/manual/en/function.echo.php#52881

Share your thoughts & feedback

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: