Many languages have classes that make concatenating a bunch of strings much faster. For instance in .Net there is StringBuilder and in Java there is StringBuffer. Is there any such class in PHP that allows for the efficient concatenation of many strings into a single string? Or possibly, does PHP have some inbuilt functionality that would make it efficient by default if, for instance, I wanted to make a string that was 100,000 characters long, and build it by adding the characters on, one character at a time?
3 Answers
Using implode() (your strings must be in an array) is almost 3 times faster than using the .= operator.
Edit: OK I rushed things. It not, not always anyway. The behavior is not linear.
I run some tests (100 iterations).
10.000 elements:
regular concat: 0.00069347143173218 sec
implode(): 0.00050755023956299 sec (slightly faster)
100.000 elements:
regular concat: 0.0088809585571289 sec
implode(): 0.0054086112976074 sec (much faster)
1 Comment
StasM
Good idea, since implode() uses internal "smart string" functionality which uses adjustable pre-allocated buffer - while .= reallocates on each concatenation.
There is no such thing in PHP. If you're generating a web page, consider use echo to output each variable rather than concat them. Use output buffer may also help.
2 Comments
Kibbee
I'm not sending them to the output right away. I want to build up a string, and then do some processing on it.
Chinoto Vokro
What was meant by the output buffer comment is to do this:
<?php ob_start(); echo some_stuff(); echo other_stuff(); echo more_junk(); $built_string=ob_get_clean();?> It's actually a very nice technique because you can leave the php context and get html syntax highlighting (or javascript if inside a script element): <?php ob_start();?><a href='/donate?token=<?=$token?>'><img src='donate.png' alt='NEED MONEY!'/></a><?php $donate_link=ob_get_clean();?>There is no built-in functionality.
Use the general .=
4 Comments
Kibbee
But if that works like most other languages, that is terribly inefficient. Are you saying there is absolutely no other way, or should I go about creating my own class that is more efficient at concatenating strings?
zerkms
@Kibbee: how could you create your own class that concatenates strings in more performant way? You want to store pieces as a private array member and
implode it on demand? It could be a little faster, but I'm not sure it is the place where you can improve anything significantly.Kibbee
The same way it's implemented in any other language. Basically you start out with some fixed size array. Keep an index of where the last character is. When you want to concatenate another string, you just put them in the already existing places in the array. When you run out of space, you create a new array and double the size. That way you aren't constantly creating new arrays, and recopying the entire string every time you want to concatenate a single character.