String builder in Julia?

question

#1

Is there anything like a string builder in Julia? What is the recommended approach to build a string by iteratively concatenating parts to it?


#2
  1. Create an IOBuffer, buffer = IOBuffer().
  2. Print to the buffer, print(buffer, "Hello")
  3. Take from the buffer, String(take!(buffer))

#3

And if you really need to squeeze out performance you can pass sizehint to IOBuffer to preallocate memory if you can estimate the size of target string.


#4

Does this approach provide better performance than string(a, b) or a * b or "$a $b"? Is it recommended when building relatively large strings, like say a web page?


#5

"$a $b" is exactly the same as writing string(a, " ", b).
string(args...) writes its arguments to an IOBuffer and then take the resulting string from it (unless all args are strings because then the output length can be preallocated).

Yes


#6

Nice, thanks!


#7

and because of this feature AFAIK e.g. string(a, b, c) will be significantly faster than IOBuffer solution (even with sizehint) if a, b and c are strings. The downside is that you need to have a, b and c before calling string. With IOBuffer you are fully dynamic (no need to have the strings upfront and no need to know how many of them you have), so this is a recommended solution for building complex strings.


#8

This is just a very thin wrapper around the IOBuffer suggestion from above. But I can never remember that, so this might make it slightly easier to use. In my mind it would make a good candidate to be moved to base at some point.