PHP中变量扩展与sprintf的性能 [英] Performance of variable expansion vs. sprintf in PHP
问题描述
关于性能,两者之间有什么区别
Regarding performance, is there any difference between doing:
$message = "The request $request has $n errors";
和
$message = sprintf('The request %s has %d errors', $request, $n);
在PHP中?
我会说调用一个函数涉及更多的东西,但是我不知道PHP在后台扩展变量名的作用.
I would say that calling a function involves more stuff, but I do not know what's PHP doing behind the scenes to expand variables names.
谢谢!
推荐答案
在所有情况下,第二个都不会更快,因为您提供的双引号字符串也必须解析变量.如果您要进行微优化,则正确的方法是:
In all cases the second won't be faster, since you are supplying a double-quoted string, which have to be parsed for variables as well. If you are going for micro-optimization, the proper way is:
$message = sprintf('The request %s has %d errors', $request, $n);
不过,由于函数调用,解析字符串,转换值等的开销,我仍然相信秒数会更慢(因为@Pekka指出了区别实际上并不重要).但是请注意,两行代码不等价,因为在第二种情况下,$ n转换为整数.如果$ n是没有错误",则第一行将输出:
Still, I believe the seconds is slower (as @Pekka pointed the difference actually do not matter), because of the overhead of a function call, parsing string, converting values, etc. But please, note, the 2 lines of code are not equivalent, since in the second case $n is converted to integer. if $n is "no error" then the first line will output:
The request $request has no error errors
第二个将输出:
The request $request has 0 errors
这篇关于PHP中变量扩展与sprintf的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!