Thanks a lot! I tested them on Julia 0.3.6:

julia> N=100000;
julia> @time concat1(N);
elapsed time: 37.870699284 seconds (23955546560 bytes allocated, 82.31% gc 
time)
julia> @time concat2(N);
elapsed time: 0.016476456 seconds (9538836 bytes allocated)

I also tried another way:
julia> function concat3(N)
           s=Char[]
           for i=1:N
               k=string(i)
               for j=1:length(k)
                   push!(s,k[j])
               end
           end
           string(s)
       end
julia> @time concat3(N);
elapsed time: 0.147099074 seconds (23086132 bytes allocated, 40.51% gc time)

Using IOString is the fastest way.

On Thursday, February 26, 2015 at 4:32:27 PM UTC+1, David P. Sanders wrote:
>
>
>
> El jueves, 26 de febrero de 2015, 9:15:38 (UTC-6), Josh Langsfeld escribió:
>>
>> It's equivalent to str = str * "def". I believe that's the case for all 
>> +=, *=, etc operators and all types.
>>
>
> That's correct. So the original code is O(n^2). A good way to do this is 
> using IOBuffer, as below.
>
> function concat1(N)
>     s=""
>     for i=1:N
>         s*=string(i)
>     end
>     s
> end
>
> function concat2(N)
>     buf = IOBuffer()
>     for i=1:N
>         print(buf, string(i))
>     end
>     takebuf_string(buf)
> end
>
> # Compile the functions and check they give the same output:
> N = 10
> println(concat1(N))
> println(concat2(N))
>
> N = 10000
> @time concat1(N);
> @time concat2(N);
>
> With N = 100000, concat2 is almost instantaneous, and I couldn't be 
> bothered to wait for concat1 to finish.
>
> David.
>  
>
>>
>> On Thursday, February 26, 2015 at 9:23:19 AM UTC-5, Jerry Xiong wrote:
>>>
>>> Considering below code:
>>> str="abc"
>>> str*="def"
>>> Is the new string "def" just be appended after the memory space of 
>>> "abc", or both strings were copied to a new momory space? Is str*="def" 
>>> equal to str=str*"def" and str="$(str)def" in speed and memory level? Is 
>>> below code in O(n) or in O(n^2) speed?
>>>
>>> s=""
>>> for i=1:10000
>>>     s*=string(i)
>>> end
>>>
>>

Reply via email to