Question

I'm always using an output variable in PHP where I gather all the content before I echo it. Then I read somewhere (I don't remember where, though) that you get best performance if you split the output variable into packets and then echo each packet instead of the whole output variable.

How is it really?

Was it helpful?

Solution

If you are outputting really big strings with echo, it is better to use multiple echo statements.

This is because of the way Nagle's algorithm causes data to be buffered over TCP/IP.


Found an note on Php-bugs about it:
http://bugs.php.net/bug.php?id=18029

OTHER TIPS

This will automatically break up big strings into smaller chunks and echo them out:

function echobig($string, $bufferSize = 8192) {
  $splitString = str_split($string, $bufferSize);

  foreach($splitString as $chunk) {
    echo $chunk;
  }
}

Source: http://wonko.com/post/seeing_poor_performance_using_phps_echo_statement_heres_why

I think a better solution is presented here ....

http://wonko.com/post/seeing_poor_performance_using_phps_echo_statement_heres_why#comment-5606

........

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.

This is my version of the solution, it echos only if the connection is not aborted. if the user disconnects then the function exits.

<?php
function _echo(){
    $args    = func_get_args();
    foreach($args as $arg){
        $strs = str_split($arg, 8192);
        foreach($strs as $str){
            if(connection_aborted()){
                break 2;
            }
            echo $str;
        }
    }
}
_echo('this','and that','and more','and even more');
_echo('or just a big long text here, make it as long as you want');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top