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?
I wrote the code at the end of this post to test the different forms of string concatenation and they really are all almost exactly equal in both memory and time footprints.
The two primary methods I used are concatenating strings onto each other, and filling an array with strings and then imploding them. I did 500 string additions with a 1MB string in php 5.6 (so the result is a 500MB string). At every iteration of the test, all memory and time footprints were very very close (at ~$IterationNumber*1MB). The runtime of both tests was 50.398 seconds and 50.843 seconds consecutively which are most likely within acceptable margins of error.
Garbage collection of strings that are no longer referenced seems to be pretty immediate, even without ever leaving the scope. Since the strings are mutable, no extra memory is really required after the fact.
HOWEVER, The following tests showed that there is a different in peak memory usage WHILE the strings are being concatenated.
Result=10,806,800 bytes (~10MB w/o the initial PHP memory footprint)
Result=6,613,320 bytes (~6MB w/o the initial PHP memory footprint)
So there is in fact a difference that could be significant in very very large string concatenations memory-wise (I have run into such examples when creating very large data sets or SQL queries).
But even this fact is disputable depending upon the data. For example, concatenating 1 character onto a string to get 50 million bytes (so 50 million iterations) took a maximum amount of 50,322,512 bytes (~48MB) in 5.97 seconds. While doing the array method ended up using 7,337,107,176 bytes (~6.8GB) to create the array in 12.1 seconds, and then took an extra 4.32 seconds to combine the strings from the array.
Anywho... the below is the benchmark code I mentioned at the beginning which shows the methods are pretty much equal. It outputs a pretty HTML table.
Firstly, if you don't need the strings to be concatenated, don't do it: it will always be quicker to do
than
However, at least in PHP5, string concatenation is really quite fast, especially if there's only one reference to a given string. I guess the interpreter uses a
StringBuilder
-like technique internally.I know what you're talking about. I just created this simple class to emulate the Java StringBuilder class.
PHP strings are mutable. You can change specific characters like this:
And you can append characters to a string like this:
Yes. They do. For e.g., if you want to echo couple of strings together, use
instead of
to get it a little faster.