String builder in Julia?

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

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

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.

3 Likes

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?

"$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

2 Likes

Nice, thanks!

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.

3 Likes

https://github.com/davidanthoff/StringBuilders.jl

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.

8 Likes

This topic was automatically closed 12 days after the last reply. New replies are no longer allowed.