Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of variable expansion vs. sprintf in PHP

Regarding performance, is there any difference between doing:

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

and

$message = sprintf('The request %s has %d errors', $request, $n); 

in 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.

Thanks!

like image 892
elitalon Avatar asked Aug 22 '11 12:08

elitalon


People also ask

What is the use of sprintf () function in PHP?

The sprintf() is an in-built function of PHP which writes a formatted string to a variable. It returns a formatted string.

Why do we need Sprintf?

Definition and Usage. The sprintf() function writes a formatted string to a variable. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step".


2 Answers

It does not matter.

Any performance gain would be so minuscule that you would see it (as an improvement in the hundreths of seconds) only with 10000s or 100000s of iterations - if even then.

For specific numbers, see this benchmark. You can see it has to generate 1MB+ of data using 100,000 function calls to achieve a measurable difference in the hundreds of milliseconds. Hardly a real-life situation. Even the slowest method ("sprintf() with positional params") takes only 0.00456 milliseconds vs. 0.00282 milliseconds with the fastest. For any operation requiring 100,000 string output calls, you will have other factors (network traffic, for example) that will be an order of magniture slower than the 100ms you may be able to save by optimizing this.

Use whatever makes your code most readable and maintainable for you and others. To me personally, the sprintf() method is a neat idea - I have to think about starting to use that myself.

like image 132
Pekka Avatar answered Sep 24 '22 16:09

Pekka


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 
like image 35
Maxim Krizhanovsky Avatar answered Sep 22 '22 16:09

Maxim Krizhanovsky