php – Text output: use echo or not?

Question:

When creating any site, HTML code is necessarily used to build blocks and generally build a site.

And often this code is in a PHP file, since there is no point in putting it into a separate file, and then including it.

Let's say there is such a PHP file and it contains the following code:

<?php

$title='Title';
$content='Content//';

echo <<<HTML
<div class='title'>$title</div>
<div class='content'>$content</div>
HTML;

But it can still be displayed like this

<?php
    $title='Title';
    $content='Content//';
?>

<div class='title'><?echo $title; ?></div>
<div class='content'><?echo $content; ?></div>

Which is the best way to use? Probably, the second method should be faster, but is it much? Or is it still possible not to think about it and write as it is more convenient?

But what if you echo a lot of HTML code?

Answer:

The benchmark will be more eloquent than any performance debate:

<?php
$title='Title';
$content='Content//';

$start_a = microtime(true);
for ($i = 0; $i<30000; ++$i) {
echo <<<HTML
<div class='title'>$title</div>
<div class='content'>$content</div>
HTML;
}
echo microtime(true) - $start_a;
?>

0.597357988358

<?php
$title='Title';
$content='Content//';

$start_b = microtime(true);
for ($i = 0; $i<30000; ++$i): ?>
<div class='title'><?php echo $title; ?></div>
<div class='content'><?php echo $content; ?></div>
<?php endfor;
echo microtime(true) - $start_b;
?>

2.21032595634

Scroll to Top