In languages like Java and C#, strings are immutable and it can be computationally expensive to build a string one character at a time. In said languages, there are library classes to reduce this cost such as C# System.Text.StringBuilder
and Java java.lang.StringBuilder
.
Does php (4 or 5; I'm interested in both) share this limitation? If so, are there similar solutions to the problem available?
StringBuilder analog is not needed in PHP.
I made a couple of simple tests:
in PHP:
in C# (.NET 4.0):
Results:
10000 iterations:
1) PHP, ordinary concatenation: ~6ms
2) PHP, using StringBuilder: ~5 ms
3) C#, ordinary concatenation: ~520ms
4) C#, using StringBuilder: ~1ms
100000 iterations:
1) PHP, ordinary concatenation: ~63ms
2) PHP, using StringBuilder: ~555ms
3) C#, ordinary concatenation: ~91000ms // !!!
4) C#, using StringBuilder: ~17ms
If you're placing variable values within PHP strings, I understand that it's slightly quicker to use in-line variable inclusion (that's not it's official name - I can't remember what is)
Must be inside double-quotes to work. Also works for array members (i.e.
)
no such limitation in php, php can concatenate strng with the dot(.) operator
outputs "hello world"
When you do a timed comparison, the differences are so small that it isn't very relevant. It would make more since to go for the choice that makes your code easier to read and understand.
No, there is no type of stringbuilder class in PHP, since strings are mutable.
That being said, there are different ways of building a string, depending on what you're doing.
echo, for example, will accept comma-separated tokens for output.
What this means is that you can output a complex string without actually using concatenation, which would be slower
If you need to capture this output in a variable, you can do that with the output buffering functions.
Also, PHP's array performance is really good. If you want to do something like a comma-separated list of values, just use implode()
Lastly, make sure you familiarize yourself with PHP's string type and it's different delimiters, and the implications of each.
I was curious about this, so I ran a test. I used the following code:
... And got the following results. Image attached. Clearly, sprintf is the least efficient way to do it, both in terms of time and memory consumption. EDIT: view image in another tab unless you have eagle vision.