2 ms·
> 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
by 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.