开发者

PHP: One big echo (or print) VS many small echo (or print)

开发者 https://www.devze.com 2023-01-31 15:56 出处:网络
I should echo a table with 1000 rows of data, can I echo all the data in one string o开发者_StackOverflow社区r is it better to echo a row per time?According to http://phplens.com/lens/php-book/optimiz

I should echo a table with 1000 rows of data, can I echo all the data in one string o开发者_StackOverflow社区r is it better to echo a row per time?


According to http://phplens.com/lens/php-book/optimizing-debugging-php.php (see last third of article) you should use one big echo statement, and use single quotes instead of double quotes, so PHP hasn´t to check for variables within the string.

simple test for support:

$bgn = microtime(true);
for ($i=0; $i<=1000; $i++)
{
  echo $i;
}
echo "\n", round(microtime(true)-$bgn, 4), "\n";
unset($bgn);
$bgn = microtime(true);
$b = '';
for ($i=0; $i<=1000; $i++)
{
  $b.=$i;
}
echo $b;
echo "\n", round(microtime(true)-$bgn, 4), "\n";
?>

First run return 0.0022, while second run return 0.0007 ... however this is small set of data, memory usage is quite small.


I would echo line by line. This way you save memory (no need to load all lines in memory before outputting them).


This is old, and some of it is outdated, but you should still definitely read How Long Is a Piece of String?

That said, unless you've already heavily optimized everything else, it's unlikely that echo is your bottleneck.


echo row per time, using lesser buffer memory and less memory (you don't need to use a variable to hold the data)

based on the tested that I conducted for the selected answer, it show opposite


It depends on your aim. Time consumption usually is no issue depending on the number of fields, so is the mermory usage for this action (todays memory is large enough to cause no problems withonly 1000 rows).

My feeling tells me it might be more practical to echo it line by line in order to do modifications, but i think it is not a big deal at all. Do what you like.


As Pekka said, it doesn't matter. Do it in the way that makes your code best readable (by using a template preferably, instead of just lame echo within mysql fetch array loop).

When (if ever) it become a bottleneck - profile it first, and optimize then. Based on the real life numbers, not rumors.

As for the particular 1000-rows table - paginate it, silly. just paginate.
Make your app not to do useless job. That's the real secret of optimization.

0

精彩评论

暂无评论...
验证码 换一张
取 消