Accumulating strings dynamically

I have to dynamically accumulate strings and for each string simply accumulate characters in an array

push!(word, c)

and then using this nifty one-liner to convert to a string

foldl(*, word)

I’m just wondering if that’s the best way to solve the problem ?

julia> word = ['a','b','c'];

julia> join(word)
"abc"

No, write to a buffer: create buf = IOBuffer(), accumulate characters as print(buf, c), and then do String(take!(buf)) at the end.

2 Likes

To be clear, this is exactly what join does internally, right? And the advantage of this over using join is just that you also skip the unnecessary collection into a Vector{Char} ?

1 Like

Yes.

@stevengj is the winner ! :slight_smile:
@yha comes in second place

and I came in last :frowning:

The foldl method is slowest because it does the most allocations. What’s particularly interesting is that the IOBuffer method uses about 1/3 the allocations of using join. And join uses about 1/2 the allocations of foldl.

Thanks everyone