Has someone made a StringBuilder
implementation in PHP?
Fortunately, you don't need to use StringBuilder anymore - the compiler can handle it for you. String concatenation has always been a well-discussed topic among Java developers. It's been costly.
StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
StringBuilder has overhead, so string is faster for limited concatenations. If you are going to append or modify thousands of times (usually not the case) then StringBuilder is faster in those scenarios.
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.
Note:
This answer is from 2010, there might be stringbuilders that can improve the performance by now (judging from the comments below). I have not worked with php for a long time so my knowledge is not up to date. This answer might be out dated.
The following question might provide interesting information as well, all tough their conclusion seem to be the same.
php String Concatenation, Performance
Why do you want to use a StringBuilder? Strings in php are mutable. Therefore performance is not an issue.
Just build string like this
$string = "start"; $string .= "appended string"; $string .= "appended string"; etc.
You can use sprintf
which is only a basic version but requires no extra libraries, examples Follow
$String = "Firstname %s, lastname %s, Age %d"; echo sprintf($String,"Robert","Pitt",22);
And also handles type casting and position replacements:
$format = "The %2$s contains %1$d monkeys. That's a nice %2$s full of %1$d monkeys."; sprintf($format, $num, $location);
All though i do like the look of jacob's answer :)
taker a look at the great functionality of t his function and its sister function here: http://php.net/manual/en/function.sprintf.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With