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

Is there any speed difference between these two versions?
<?php echo $var; ?>
<?=$var?>
Which do you recommend, and why?

Performance difference is insignificant. Moreover, with use of APC, performance difference is zero, null, nada.
Short tags are problematic within XML, because <? is also markup for XML processing tag. So if you're writing code that should be portable, use the long form.
See short_open_tag description in http://www.php.net/manual/en/ini.core.php

Technically the parser has to parse every character of the longer version, and there's a few more characters for every transfer.
If your webserver doesn't "pre-compile" (ie: cache tokenized PHP pages) then there is a slight performance difference. This should be insignificant except, perhaps, when you start talking about billions of runs.

Performance wise it is insignificant.
Proper usage says to use the longer one, as it is more portable. Personally? I do the shorter one.

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

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.

in php 5.3 short tag ASP-style <% %> support will be deprecated, try to avoid this and rewrite the code to the '<?php echo' format, because u cant use <?xml ?> inline for example.

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.

I think the second one requires the short_open_tag (in PHP.ini) to be set to true.
Meaning there is a chance it's turned off on some webservers.

The speed difference depends on how fast you can type those 9 extra characters.
It can also improve the readability of your code, but this is debatable.
If your talking about execution-speed there is no noticable difference.

Don't try to optimize with these, it's useless. Instead, deactivate allow_short_tags (because of problems when loading XML files) and write clean, readable and understandable code.
Even if there may be a slight difference (which is definitely lower than 10%), it's useles to optimize with it. If your scripts are slow, look at your loops first. Most of the time you can win a lot more performance by optimizing the programms flow than by using strange syntax.

Related

Is <? ... ?> valid shorthand PHP and will it always work? [duplicate]

This question already has answers here:
Are PHP short tags acceptable to use?
(28 answers)
Closed 8 years ago.
I sort of discovered by accident that
<?php ... ?>
can be shortened to
<? ... ?>
Is this a bad idea? In some cases? What cases are they? Are there anymore shorthand examples? I am aware of shorthand examples involving conditional statements but I don't find them easier to read.
Please link me if this has been answered elsewhere, but I could not find it via a search. Maybe I'm not using the right keywords.
This shorthand has been available for a very long time, but its use is discouraged (and nowadays disabled by default) because of various incompatibilities with other languages — ambiguity with ASP's ability to accept <? x ?>, and with various XML constructions, are two obvious examples.
Opt not to use it.
By contrast, the <?= x ?> shorthand (equivalent to <?php echo x ?>) has had a resurgence in popularity and is enabled by default since PHP 5.4, because it does not suffer from the same problems.
As always, consult the documentation for canonical information on such things.
The shorthand tags are only enabled in certain setups. They are discouraged. See the PHP manual entry for the tags: http://www.php.net/manual/en/language.basic-syntax.phptags.php
PHP also allows for short open tags (which are discouraged because they are only available if enabled with short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option.
As far as other shorthands, no others exist. The <?= ?> shorthand could possibly be considered one, though it's only usage is to output a variable (as mentioned in another answer to this question). The omission of the closing ?> is sort-of one. It's handy for documents that contain nothing beyond PHP code. This technique is also mentioned in the manual entry I linked above.
Will it work? In some cases. PHP has a few opening tags available, take a look here. But you should be careful as it depends on the php configuration (usually /etc/php.ini or /etc/php/php.ini). There is an option short_open_tag = On. if it's not enabled, the code will be rendered in the view and won't be executed as php code.
As blakeo_x said, the shorthand is only valid if the PHP configuration file has it enabled.
It is discouraged because you might have to run it on a different server where shorthand is not enabled. Hence try to stick to the longer version <?php instead.

Difference between # and // in php?

<?php
# some comment
?>
and
<?php
// some comment
?>
are used for single-line code commenting in PHP, and that former comes from shell scripting and // comes from C++.
However I am curious to know if there are any differences between using // and # for single line commenting and anyone has come across cases specific cases where one or other should not be used.
Only difference I could think of is there is one character in '#' and two in '//' so perhaps will there in larger scripts some small size and/or performance gains ??
For me it's easier to type // by double pressing the key on my keyboard moving just my right pinky one key down and pressing it two times.
If I want to do # I need to use both hands and the movements are "bigger" ;). It's the same for echo and print.
But in print and echo "scenario" you can hear an argument that one function is a little slower, however I am not sure right now which one ;) but it's really something that is no deal-breaker when optimizing for code I guess.
According to this topic echo is a little faster:
Should I use echo or print in php scripts?

Curly braces or colon-endif statements in PHP - which one provides better performance and code compatibility?

I was looking through many snippets of code, and I have found that people can use the following two methods in an if statement:
Method 1:
<?php
if ($condition) {
// Do this
}
?>
Method 2:
<?php
if ($condition):
// Do this
endif;
?>
So which method is more compatible with PHP compilers and versions with PHP, or is there no discernible difference between the two?
Most of the time the alternative (endif) syntax is used in view scripts. It's often hard to see/notice the end of an if statement since a curly brace only takes up one character, when you're at the bottom of a file, it's hard to tell if it's the end of an if or a foreach. For example:
<?php if ($condition): ?>
<div>a huge block of html</div>
<?php endif; ?>
They are both exactly equivalent. Consult your organization's style guide to determine which you should use.
This alternative syntax is in no way different than the, perhaps, more familiar syntax. Just don't mix the two. Similar syntax exists for while, for, foreach, and switch.
Typically you should choose your preferred syntax based upon readability, and your teams preference.
What really might throw you is when you begin to see "if statements" which misuse logical conjunction operators like the following:
isset( $value ) AND print( $value );
As I've seen until now, in my app, there is no difference between them, but you can have a lot of problem if you'll mixt them without a rule because it's possible to get some errors and you will search a curly but you have not used curly.
Choose one syntax an use exclusive.
The only difference is seen in very large documents and projects. My company uses braces rather then endif, endelse... as we work on very large projects. When you compare file sizes there is a benefit to using braces. Smaller files load faster so we work to reduce every byte we can. We comment out the end brace to make it easier to identify on testing and then delete all comments for production.

PHP Short tags - Are they slower than regular syntax?

Is writing
<?=$variable?>
slower than
<?php echo $variable; ?>
In other words, what does the server interpret faster?
I can guarantee you with absolute certainty that it won't matter one bit. :)
I don't think there will be a huge difference - but short-tags essentially have to get essentially converted first into the normal syntax when executed. I expect the differance is minimal - I have never tried to benchmark it!

Php: what's the difference between while...endwhile; and while { // stuff here }

What's the difference between
while (expression):
// do stuff
endwhile;
and
while {
}
There is no functional difference.
In practical use I find that:
while (expression):
// do stuff
endwhile;
Is more readable for the designers when you are embedding php code within html. IE:
<? while ($cssClass = array_pop($array)): ?>
<li class="<?=$cssClass?>">
<? endwhile; ?>
Whereas:
while {
}
Is more readable within a php code block.
There's no difference, it comes down to personal preference.
The difference is negligible when the code is actually run, but when coding I find that typing the brackets is (1): quicker, (2): more conventional, and (3): allows for less chance of error (endwhle anyone?).
As a bonus, the editor I use auto-formats the while loops (with brackets, by default) and down the road, if anything is off, the built-in bracket-matching function will catch it.
There's no real difference when writing code.
There can be a difference in levels of convenience in very special circumstances. For example, suppose you are writing a template engine that converts template code to native PHP code which is then cached and executed directly for speed.
In this case, the fact that while...endwhile; avoids using braces may allow you to simplify your parsing algorithm if e.g. it recognizes variables that should be substituted with a syntax like {$var}, which also uses braces.
Of course this is a pretty small benefit in a really extraordinary situation, but you take what you can. :)

Categories