Reputation: 305
I'm almost sure the answer to this is "None at all!" but I'll ask anyway. If you have a conditional statement in PHP which echos a line of html, is there any difference performance-wise between these 2 examples:
<?php if ($output) { ?>
<h2><?=$output;?></h2>
<?php } ?>
and
<?php if ($output) { echo "<h2>".$output."</h2>"; } ?>
Upvotes: 3
Views: 297
Reputation: 5062
I had to know so ran a few different blocks in a loop of 10000 iterations. Lesson learned: Don't bother. Write the code to be readable and maintainable. Use the MVC pattern... :)
time: 2.66 microseconds
<? if ($output) { ?>
<h2><?=$output;?></h2>
<? } ?>
time: 1.65 microseconds
<? if ($output) { echo "<h2>$output</h2>"; } ?>
time: 1.65 microseconds
<? if ($output) { echo "<h2>".$output."</h2>"; } ?>
time: 1.64 microseconds
<? if ($output) { echo '<h2>'.$output.'</h2>'; } ?>
Upvotes: 1
Reputation: 18266
Why not just test it out ? by sniffing or taking a look at the source for a page in your favourite browser.
Upvotes: 1
Reputation: 75704
Why do so many PHP developers try to optimize such things? It's the same as the debate about single- and double-quoted strings. If these performance differences matter in any way, you should really be using another language.
Upvotes: 3
Reputation: 49376
The answer literally is "None at all". Consider
<span>
<?php
echo $myMessage;
?>
</span>
and
<?php
echo "<span>\n";
echo $myMessage;
echo "</span>";
?>
I'm going from memory (of a few years ago), but at that point the Zend bytecode compiler produces essentially identical output; "literal" HTML was compiled into an echo statement containing the text.
Upvotes: 6
Reputation: 27285
If you are really into micro optimization, you should start with changing
echo "<h2>".$output."</h2>";
into:
echo '<h2>', $output, '</h2>';
(no variable expansion and no string concatenation)
Upvotes: 4
Reputation: 3665
I don't think there is a noticeable performance difference. I use whatever variant makes my code more readable.
Upvotes: 9
Reputation: 16122
The <?= ?>
tags are invalid, unless you have short_open_tags enabled, which is not recommended.
Upvotes: 5
Reputation: 1525
I prefer option 1 as it makes it easier to edit the HTML in most cases - specially when dealing with divs with inner content.
Performance is negligible in both cases.
Upvotes: 1
Reputation: 48710
The performance would be negligable and not worth worrying about in practice. The first option would be the preferred method as it's more readable and uses php as it was meant to be used (templating).
Theoretically though, I'm guessing the first method would be faster as the language has less to parse. The straight html text is just returned without processing.
Upvotes: 2
Reputation: 29536
This is called micro optimization, you can't rely on such performance differences
But this is better on performance in by few nano seconds
<?php if ($output) { ?>
<h2><?=$output;?></h2>
<?php } ?>
Upvotes: 2