Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder for PHP

Has someone made a StringBuilder implementation in PHP?

like image 363
Mark Avatar asked Nov 18 '10 18:11

Mark


People also ask

Is StringBuilder still necessary?

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.

What is the purpose of StringBuilder?

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.

Is StringBuilder faster than string C?

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.

Which is better string or StringBuilder?

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.


2 Answers

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. 
like image 80
Mark Baijens Avatar answered Oct 05 '22 17:10

Mark Baijens


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

like image 20
RobertPitt Avatar answered Oct 05 '22 15:10

RobertPitt