Good point, printing to the the IOBuffer is the fastest option:

strings = [randstring() for i in 1:1000000]
function f1(strings)
    a = IOBuffer()
    for s in strings
        print(a, s)
    end
    takebuf_string(a)
end

function f2(strings)
    join(strings)
end

function f3(stings)
    buf = Any[]
    for s in strings
        push!(buf, s)
    end
    join(buf)
end

assert(f1(strings)==f2(strings)==f3(strings))

@time f1(strings)
@time f2(strings)
@time f3(strings)
;

elapsed time: 0.038563872 seconds (24778644 bytes allocated)
elapsed time: 0.054497171 seconds (24778692 bytes allocated)
elapsed time: 0.289836491 seconds (89548756 bytes allocated, 35.00% gc time)




Am 17.02.2015 um 18:07 schrieb Jameson Nash <[email protected]>:

> There is an IOBuffer type that works well as a string builder
> On Tue, Feb 17, 2015 at 11:56 AM René Donner <[email protected]> wrote:
> You could use
> 
> a = Any[]
> while ...
>   push!(a, somestring)
> end
> join(a)
> 
> 
> 
> Am 17.02.2015 um 15:28 schrieb Maurice Diamantini 
> <[email protected]>:
> 
> > Hi,
> >
> > In Ruby, String is mutable and there is the << operator to accumulate
> > a string at the end of another one.
> >
> > I Julia, String is immutable and so, I use the contatenation operator
> > when I need to build a large string:
> >
> >     txt = ""
> >     while ...
> >         txt *= "yet another line.\n"
> >     end
> >     # do something with txt
> >
> > This is very slow because it build a new (more and more large) string at 
> > each
> > iteration.
> > Is there another way in Julia to efficiently build such a string?
> > Or is there another type one can use for that task (Buffer, Array, ....)?
> >
> > Thanks in advance,
> > -- Maurice
> 

Reply via email to