I have long wondered if operations on strings are expensive (memory and / or computationally)? In Java, C # languages we meet a special class of StringBuilder type, which is the recommended way of creating strings (it is the optimal version of “ordinary” strings – optimal in terms of performing operations on them). In the case of PHP, we do not have such a class – there is only simple, ordinary concatenation.
I did a simple research and it turns out that concatenation does not allocate more memory than creating the entire string ad hoc, but has a slight effect on the time it takes to perform such an operation (it is related to destroying and creating a new string):
// Long string created ad hoc
$ str = 'Long string, very long string, several thousand characters….' ;
// Same inscription, divided into parts and "combined"
$ str = 'Long string, very long string,' ;
$ str . = 'Several thousand characters….' ;
In both of the above cases, the memory occupancy is the same, but the string creation time differs by about 14-17% in favor of the string created in one rewrite (without concatenation). However, this is not a big difference, taking into account that creating a string with a length of over 4,000 characters takes about 0.000026 seconds.
The test was carried out on two machines (laptop and leased server, both running PHP 5.2.6).
Interestingly enough, assigning a string to another variable does not allocate additional memory, as in this case:
$ str = 'Long string, very long string, several thousand characters….' ;
$ tmp = $ str ;
Provided, however, that the newly created inscription is not modified:
$ str = 'Long string, very long string, several thousand characters….' ;
$ tmp = $ str ; // No memory allocation for $ tmp
$ tmp . = ” ; // Memory allocation
In other words, the implicitly variable is substituted with “pseudo-references” – however, if the newly created string changes, a new memory location is created. This also happens when passing arguments to a function / method.
To free the memory occupied by a given string, it is enough to do one of two ways:
// The first way - clears the variable
$ str = null ;
// The second way - more kosher - eliminates the variable
unset ( $ str ) ;