Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Speed - Many Echos vs Building a String

Wondering if anyone knows if either of these methods would produce an output faster:

Method 1
for ($i=1;$i<99999;$i++) {
echo $i, '<br>';
}

or

Method 2
for ($i=1;$i<99999;$i++) {
$string .= $i . '<br>';
}
echo $string;

Thanks for any input you have.

like image 885
Chris Avatar asked Jun 05 '10 21:06

Chris


2 Answers

Method 1 Uses less Memory and CPU and is "faster" (Less server load) But the output bottleneck most likely is the browsers downloadspeed.

If you don't buffer the output, the browser can start downloading stylesheets, images, etc sooner.
(while your script is waiting for some query results)

Check out the answers on PHP Optimalization or http://code.google.com/speed/articles/optimizing-php.html for more tips.

like image 116
Bob Fanger Avatar answered Oct 20 '22 05:10

Bob Fanger


Method 1 seems like it'd be faster. Method 2 will have to spit out a bunch of CONCAT opcodes for each iteration of the loop, and the very long string will be built in memory until you're ready to send it. Method 1 on the other hand will just be two ECHO opcodes per loop, and then PHP/your webserver is free to flush content to the client before you've fully finished, if it wants to.

Of course, if you're concerned about micro-optimisation, you're going to get far better performance by using an opcode cache, caching proxy, or something like hiphop.

like image 26
Chris Avatar answered Oct 20 '22 06:10

Chris