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