Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php / templating vs echoing

i would like to know which one is the best for performance:

1- use smarty template ( or any other better)

<?php
$Smarty = new Smarty();
// set all the default variables and other config
$Smarty->assign('var1', 'hello');
$Smarty->assign('var2', 'world');
$Smarty->display('page.html');

2- use this code:

<?php
$var1 = 'hello';
$var2 = 'world';
echo "$var1 $var2";

3- use this code:

<?php
$var1 = 'hello';
$var2 = 'world';
echo $var1 . " " . $var2;

based on these 3 examples i cant think about a new one, which one is best to use when performance

note: of course i have more variables than this example.

thanks

like image 769
Neil Avatar asked Nov 17 '11 03:11

Neil


2 Answers

As far as I remember, concatenating PHP variables (as in your third example) is faster than using "$var1 $var2" given a mix of variables and constant strings as each token is evaluated on the fly (which is bad).

So, between 2 and 3, I believe it depends on context: If you have a long string with a mix of variables and constants, then method 3 would be faster. Otherwise, if it's identical to your example, 2 might be faster (however, the difference is negligible and therefore should be a moot point).

Using a templating engine will always be slower than raw code.


Now if you don't have a very good reason to not use a templating engine, you should by all accounts use one. Why?

  • Separation of concerns: Your PHP shouldn't care about your HTML and vice versa.
  • Maintenance: Maintaining can become a nightmare when you mix HTML and PHP (or any other language for that matter) and should really be avoided at all cost (unless you're doing something blindingly trivial).
like image 124
Demian Brecht Avatar answered Sep 20 '22 11:09

Demian Brecht


Performance only? In the first example, you are using Smarty, a fairly weighty library composed of thousands of lines of PHP code. In the next two, you are using three lines of PHP only. Of course those two will be much faster, with less overhead, since PHP doesn't have to parse Smarty first.

As for whether string concatenation or substation of variables, and which quotes etc. are faster, it's a micro-optimization not likely to make a difference at a sub-Facebook scale. One or the other is merely saving nanoseconds. You can read live comparisons on this page: http://www.phpbench.com/ if that helps.

like image 2
JAL Avatar answered Sep 19 '22 11:09

JAL