打印时的PHP性能

Is there any difference between:

echo "<p>" . $var . "</p>";

and

<p> <?php echo $var; ?> </p>

when it comes to performance?

Joel

The second is slightly quicker as it doesn't have to concatenate the strings together.

But really you're only going to see an increase in performance if this is repeated a huge number of times.

Also, as a slight side point, using the multiple parameters of the echo function, such as:

echo("<p>",$var,"</p>");

is also quicker than concatenating the string.

<p> <?php echo $var; ?> </p> Is faster because

  1. the HTML part is not parsed by the PHP compiler
  2. there is no string concatenation done

Extra:

  1. 'string' is faster than "string"
  2. <?php echo $var; ?> can be shortened to <?=$var?>

Here's something to play with if you want.

<?php
$start = microtime(true);
for($i = 0; $i < 10000; $i++){
?>
<?php
echo "<p>" . rand(0,9) . "</p>";
?>
<?php
}
echo '<br /><br />TIME: '.(microtime(true) - $start);
?>

vs.

<?php
$start = microtime(true);
for($i = 0; $i < 10000; $i++){
?>
<p><?php echo rand(0,9) ?></p>
<?php
}
echo '<br /><br />TIME: '.(microtime(true) - $start);
?>

I'd like to see your times in the comments.

Even faster is this

<p><?=$var?></p>

Using <p> <?php echo $var; ?> </p> than echo "<p>" . $var . "</p>"; reduces server side operation. Even though in this case it is neglegible, it does have a difference.

I agree with @laurencek, only in case of a repeated unnatural number of times performance can be committed.

I would recommend PHP Benchmark from Chris Vincent. Here it's documented very well. Don't forget to reload the page a few times to get a better result.

To comment the answers for shorten your version of code to <?=$var; ?>:
Always thing about interoperability. Not all webservers out there allow short tags and when you want to move your code to another server or want to publish the whole thing, it could lead to problems.

This is an almost useless micro-optimization. If you are not in a very special case and you still need to squeeze some ms after the real good optimization (caching, buffers, good SQL etc.) you better start thinking about using something which is not php.

Just choose one method and stick to it so your code is readable. If you want the fastest one, benchmark it on your server as some configurations may change your results.