PHP performance: appending vs prepending strings
Which is more performant: ($longstring . $longstring) . $longstring
, or $long开发者_开发问答string . ($longstring . $longstring)
? Is PHP's concatenation operator left- or right-associative? Is its associativity optimal, or should I override its associativity with parentheses?
It really, really doesn't matter. The difference is a few milliseconds at best.
Write it as suits best your coding style and future maintainability.
$x . $y . $z
is the same as ($x . $y) . $z
However, there is no performance to be gained via either approach. It's like:
// ($x . $y) . $ z
$tmp = $x . $y;
return $tmp . $z;
vs
// $x . ($y . $ z)
$tmp = $y . $z;
return $x . $tmp;
In both cases, the same amount of concatenations are occurring. If one method were faster (but neither are), then it would be dependent on the lengths of $x
, $y
, and $z
. (i.e., Is it faster to append a short string to a long string, or to append a long string to a short string is really the question you are asking. Without testing, I'd say the difference is insignificant.)
Now, these are different: $x .= $y
and $x = $y . $x
. The first is the single ASSIGN_CONCAT
append operation, which might be measurably faster than prepending (CONCAT
, ASSIGN
). Note that $x = $x . $y
, while functionally equivalent to $x .= $y
, is also two operations. So that style of appending would have the same performance difference (if any) as prepending.
As Pekka said, it really doesn't matter and I don't think there's any serious benchmark about it. You should try it out and measure if you really want to know.
As for associativity, I think the most common concat functions are left to right.
http://www.php.net/manual/en/language.operators.string.php
The two should be no difference between the two. Both first allocate an additional 2n string for the ($longstring . $longstring), and then an additional 3n string for the the whole thing. Parens confuse me, because they are suppose to convey some meaning, but in this case they are simply there because you think it's faster. If there's nothing special about either group, $s1 . $s2 . $s3
is preferable.
Micromanaging such tiny details for performance reasons is a waste of time. As Pekka said, it gives an incredibly tiny difference in speed. You could spend the same amount of time looking for things that could really improve the performance significantly.
Edit: If the strings are really long and really many, and are slowing down the requests for real, you should consider passing them without creating a single string. Keep an array of them and then output them or store them without concatenation.
精彩评论