Is there anything like a string builder in Julia? What is the recommended approach to build a string by iteratively concatenating parts to it?
- Create an
IOBuffer
,buffer = IOBuffer()
. - Print to the buffer,
print(buffer, "Hello")
- Take from the buffer,
String(take!(buffer))
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.
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
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.
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.
This topic was automatically closed 12 days after the last reply. New replies are no longer allowed.