4 ms·
I dunno. I still haven’t seen an implementation of a string builder which leverages the immutability of strings in modern languages. String building is mainly
by jbverschoor 7y ago
I dunno. I still haven’t seen an implementation of a string builder which leverages the immutability of strings in modern languages.
String building is mainly about concatenating objects. Most of the times they are actual strings, other times they are object which get transformed into strings. As long as the object is immutable, you can do the transformation at a later stage.
You can keep appending the strings to an array or linked list, and only make the built strong concrete when it’s asked for - in Java that’s toString(), or to compare strings.
The benefit is that you don’t have to allocate and reallocate (fragment) memory when appending, because you’ll know exactly what the required capacity will be.
You can expand the append() with any immutable object, but strings and numbers make the most sense.
- mikeeeek 7y agointeresting idea, although not obvious this would have the intended affect. E.g., consider a string search across 10 different string objects (thus 10 different backing arrays), vs a search across a single array. Much more likely for increase in cache misses when you hit 10 different arrays at potentially 10 different locations in memory. Also, this implies some copy-on-write semantics. At first thought, this makes code significantly more complex.
- jbverschoor 7y agoYou can always make the string concrete for certain operations. Most of the string building is usually just concatenation
- Someone 7y ago> The benefit is that you don’t have to allocate and reallocate (fragment) memory when appending, because you’ll know exactly what the required capacity will be. How likely is that in real life? If, for example, you append a number to your buffer, figuring out how long the resulting string will be takes time, and means doing part of the string conversion twice. Also, in many languages, figuring out whether an object’s toString method always returns the same string (something that is different from the question whether the object is immutable) can be very difficult. Finally, "You can keep appending the strings to an array or linked list” also can require reallocations, because you may not know the number of items appended up front. ⇒ Doing it the way you suggest may be faster, but it definitely isn’t a slam dunk.