Inline Strings vs. Concatenation in PHP: Speed Implications
Consider the following PHP code:
$foo = 'some words'; //case 1 print "these are $foo"; //case 2 print "these are {$foo}"; //case 3 print 'these are ' . $foo;
Is there a significant performance difference between cases 1 and 2?
Historically, there may have been a performance difference between single-quoted inline strings (case 1) and double-quoted strings containing variables (case 2). However, this difference has become negligible in PHP versions since at least January 2012.
What about the performance difference between cases 1/2 and 3?
Concatenation using the period (.) operator (case 3) has consistently been slower than using inline strings, regardless of whether the inline strings are single-quoted or double-quoted. This is because concatenation requires additional steps to evaluate the variable and concatenate it with the string.
Conclusion
Based on empirical evidence, the speed difference between using inline strings and concatenation in PHP5 is negligible. Performance considerations should not be the primary factor in choosing between these methods. However, it's important to remember that performance improvements in later versions of PHP may not be reflected in older versions.
The above is the detailed content of Is Concatenation in PHP Really Slower Than Inline Strings?. For more information, please follow other related articles on the PHP Chinese website!