I’ve pretty much wasted 10 hours over the past 2 work days fretting over a PHP script taking over a second to execute on the server and the culprit in all this was Apache. Let me explain, the script was fairly complex and part of large CMS website with heavily integrated user/community systems and a few public and private APIs for external projects. Basically there are a lot of things that could cause problems, however, after separating each system, which was a tangled messed, I traced the bottle neck of the 1 second execution time down to the template object, used on virtually every page.

Loading just HTML from cached template files using either of PHP functions include/require/readfile accounted for roughly 99% of the page load time. The larger the HTML file the larger the lag. In the end rather than printing the text straight away I decided to try and load the files information in to PHP then echo it. Loading of the HTML in to PHP took roughly 3ms where as echoing took roughly 0.9 seconds.

The closer the user was to the server in the world the less time it took to echo the statement. Obviously PHP was getting hung up with waiting for the user to receive the data. Somehow we managed to stumble across the apache variable SendBufferSize which was set surprisingly low (only 4kbs). The PHP script had to wait for this buffer to clear before it could send more information to apache to then send to the user.

So far our solution has been to set SendBufferSize to 128kb in the hope that no HTML is going to get anywhere close to this size. If it does we will have to deal with that later. What I personally cannot work out is why this is set so low by default? Ram is never going to get swamped on a server by setting this buffer higher unless your executing 10k+ scripts all at once. Which means the PHP script is over in 20ms rather than a second.

So if your scripts are lagging due to the include function or because of an echo statement then your sending too much data to apache before it can clear it. Set SendBufferSize higher and you’ll be laughing.

Or course I should point out that this won’t really get anything to the users browers faster, but at least you’ll know that rather than constantly tweaking PHP scripts for speed, you’ll be better looking at your networking, server configuration and the amount of HTML your sending to the user.

Hope this helped.

© 2014 Altroleet Suffusion theme by Sayontan Sinha