Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a speed difference between <?php echo $var; ?> and <?=$var?>?

Is there any speed difference between these two versions?

<?php echo $var; ?>

<?=$var?>

Which do you recommend, and why?

like image 792
grilix Avatar asked Mar 19 '09 16:03

grilix


3 Answers

These two lines of code are identical.

I'm adding a late answer because nobody has demonstrated this yet, but the answer is unequivocally no, there is no performance difference specifically because there is no difference at all in how PHP executes these two lines of code.

The interpreter sees the identical code in both cases. The parser produces the exact same AST, because <?= is fundamentally identical to <?php echo. There is no difference in the instructions the interpreter runs when you write <?= vs <?php echo.

By installing php-ast you can examine the AST produced by both lines of code.

Given these two cases...

# CASE 1
<?php echo $i %>

# CASE 2
<?= $i ?>

The abstract syntax tree for both is identical:

case 1
AST_STMT_LIST
    0: AST_ECHO
        expr: AST_VAR
            name: "i"
case 2
AST_STMT_LIST
    0: AST_ECHO
        expr: AST_VAR
            name: "i"

This means PHP cannot tell the difference between these at run time, never mind experiencing some kind of performance difference.

The code to produce this output is as follows, and uses util.php:

<?php
require('util.php');

echo "case 1\n";
echo ast_dump(ast\parse_code('<?php echo $i ?>', $version=50));

echo "\n";

echo "case 2\n";
echo ast_dump(ast\parse_code('<?= $i ?>', $version=50));

echo "\n";

Optimization is irrelevant here. The choice comes down to personal preference, especially since <?= is always available, has nothing to do with short tags, has never been deprecated and is not slated to be removed from the language.

like image 62
meagar Avatar answered Oct 23 '22 05:10

meagar


No, they are identical. If you like typing a lot use <?php echo $var; ?>, otherwise just save time with <?=$var?>.

like image 22
John Rasch Avatar answered Oct 23 '22 05:10

John Rasch


Which do you recommend

Neither, unless you really want to allow HTML injection. (99% of the time, you don't.)

<?php echo htmlspecialchars($var); ?>

Or define a function that does echo(htmlspecialchars($arg)) with a shorter name to avoid all that typing.

like image 20
bobince Avatar answered Oct 23 '22 06:10

bobince