php / 模板与回显
我想知道哪一个性能最好:
1- 使用 smarty 模板(或任何其他更好的模板)
<?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- 使用此代码:
<?php
$var1 = 'hello';
$var2 = 'world';
echo "$var1 $var2";
3- 使用此代码:
<?php
$var1 = 'hello';
$var2 = 'world';
echo $var1 . " " . $var2;
基于这 3 个示例,我无法考虑一个新的模板,其中性能注释时最好使用一个
:当然我有比这个例子更多的变量。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我记得,在混合使用变量和常量字符串的情况下,连接 PHP 变量(如您的第三个示例中所示)比使用
"$var1 $var2"
更快,因为每个标记都是动态评估的(这很糟糕)。因此,在 2 和 3 之间,我相信这取决于上下文:如果您有一个混合了变量和常量的长字符串,那么方法 3 会更快。否则,如果它与您的示例相同,则 2 可能会更快(但是,差异可以忽略不计,因此应该是一个有争议的点)。
使用模板引擎总是比原始代码慢。
现在如果您没有非常充分的理由不使用模板引擎,那么您应该在所有帐户中使用一个。为什么?
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?
仅性能?在第一个示例中,您使用的是 Smarty,这是一个相当重要的库,由数千行 PHP 代码组成。在接下来的两行中,您仅使用三行 PHP。当然,这两者会更快,开销也更少,因为 PHP 不必首先解析 Smarty。
至于是字符串连接还是变量替换,以及哪些引号等更快,这是一种微观优化,不太可能在 Facebook 规模以下产生影响。其中之一只是节省纳秒。您可以在此页面上阅读实时比较:http://www.phpbench.com/(如果有帮助)。
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.