Performance of variable expansion vs. sprintf in PHP

后端 未结 6 1181

Regarding performance, is there any difference between doing:

$message = \"The request $request has $n errors\";

and

$messa         


        
6条回答
  •  抹茶落季
    2020-12-06 17:06

    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);
    

    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
    

    While the second one will output:

    The request $request has 0 errors
    

提交回复
热议问题