I have a practical question about page load time:
Suppose I want the following output:
<a class="class-a" href="www.google.com"></a>
Is it faster (with respect to load time and efficiency) to do:
<a class="<?php echo $class_a; ?>" href="<?php echo $url; ?>"></a>
or
echo "<a class='$class_a' href='$url'></a>";
This is a microcosm of a bigger issue-- if I'm using echo multiple times on the page is it better to try to condense HTML output into one variable and echo it in one go??
Thanks!
Those two really make no difference. One or two echo doesn't matter. 1000 echo doesn't matter. Really when you look at the grand scale of things, echos do not matter. I can run 5million echos per second on my laptop in a tight loop. Doing one SQL query that takes 1ms or 2ms to run means you get a difference of 5000 echo calls more or less. That's how irrelevant it is.
What you want to do is look at your code with a profiler and find the bottlenecks if you have performance problems, but don't worry about how many echos you do. And by the way you probably should use something like Twig to print HTML using templates instead of raw PHP like in your example, at least this gives you automatic HTML entities escaping, which protects you against XSS for example.
in terms of performance the second is faster because printing to an output is expensive operation. BUT you should be careful to not sacrifice an esay to read code for fast executed code.
Completely pointless micro-optimization. Whether there's a difference at all depends on what PHP runtime exactly you use, but it's going to be totally irrelevant compared with DB access of any kind, the server configuration, and bytecode caching.
This is not the kind of thing you should worry about even a second, especially if performance is important.
I have performed a test similar to what you are asking before.
Out of the two examples you posted I found that the first one is marginally slower compared to the second.
If you store the output into a buffer before hand you will use more memory and it is again marginally slower than the slowest of the two examples you gave.
As other people have pointed out it is completely irrelevant and I would put ease of maintainability and readability above any kind of speed optimisations you think you might get.