Php / templating vs echoing

I would like to know which one is best for performance:

1- use smarty template (or any other)

<?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 don’t think about the new one that is best used for performance

Note: of course, I have more variables than in this example.

thanks

+8
performance php template-engine
source share
2 answers

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

So, between 2 and 3, I think it depends on the context: if you have a long string with a combination of variables and constants, then method 3 will be faster. Otherwise, if it is identical to your example, 2 may be faster (however, the difference is not significant, and therefore should be controversial).

Using the template engine will always be slower than the source code.


Now , if you don’t have a very good reason not to use the template engine, you should use all of its accounts. Why?

  • Separation of problems . Your PHP should not care about your HTML and vice versa.
  • Service . Maintaining can be a nightmare when you mix HTML and PHP (or any other language, for that matter) and should be avoided at all costs (unless you are doing something dazzlingly trivial).
+11
source share

Only performance? In the first example, you are using Smarty, a pretty solid library of thousands of lines of PHP code. In the next two you use only three lines of PHP. Of course, the two will be much faster, with less overhead, since PHP does not have to parse Smarty first.

Depending on whether there will be string concatenation or variable substitution, and what quotation marks, etc. faster, this is micro-optimization, which is unlikely to affect the sub-Facebook scale. One or the other simply saves nanoseconds. You can read the current comparisons on this page: http://www.phpbench.com/ if this helps.

+2
source share

All Articles