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开发者_StackOverflow you have.
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.
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.
I have read that the fastest method is to enable output buffering and do many echoes. I don't have benchmarks to confirm this claim, though.
Anyway, I think this is in the realm of micro-optimization. The difference is probably measurable, but insignificant. As @Coronatus comments above, if your app were that sensitive to performance, you wouldn't be using PHP!
If you wan to micro-optimise, look to changing $i++ to ++$i as well
精彩评论