Hello. Such a strange question I had. What is more optimal from the point of view of server, browser and HTTP resources — use the echo statement several times or collect the html code into a variable and then throw it into the browser? For example:

 $html = ""; for ($i = 0; $i < 100; $i ++) { $html .= "<p> $i - <img src='images/image_$i.png' /></p>"; } echo $html; 

or

 for ($i = 0; $i < 100; $i ++) { echo "<p> $i - <img src='images/image_$i.png' /></p>"; } 
  • one
    for logical reasons, concatenating strings in a loop is a more difficult operation than immediate output. Did you try the tests? learned that this is a bottleneck? maybe your bottleneck is the user's wifi or php itself. - KoVadim
  • one
    Oh no, we came to this question again. Actually, it is optimal to cache templates, and the favorite srach echo vs print always occurs when there are much more unoptimized things in the code. If you are very, very worried about this, then you can make a comparison using the huge $ i limit and measuring the memory (I will not tell you the function, but it is there) and the past tense (microtime (true)). The truth is that a funny nuance will be that you will not have to face a really big limit in practice, and there will be a strong variation with a small one. - etki
  • one
    > Which is optimal from the point of view of server resources, browser and http protocol. The answer is given to the browser once. Until the script has completed, the browser will not receive anything. - etki
  • one
    If output buffering is disabled, the first option will be faster, and in the usual case the second one. But if for some reason you want to display everything in $ html (for example, this variable is used elsewhere), you can do it through ob_start () functions and so on. but here it is not necessary. - zb '
  • If your task is to speed up the slow page rendering, I suspect that replacing echo with concatenation will never be the solution. Get real optimizations. - VladD

1 answer 1

Reply from comments:

Etki : The answer is given to the browser once. Until the script has completed, the browser will not receive anything. Therefore, from the point of view of the HTTP protocol, both options are equivalent.

zb : However, from the server’s point of view, if output buffering is disabled, the first option will be faster, and in the usual case the second one. But if for some reason you want to display everything in $html (for example, this variable is used elsewhere), you can do this by buffering the output using ob functions (ob_start (), etc.).