El domingo, 15 de noviembre de 2015, 18:00:09 (UTC-6), David P. Sanders
escribió:
>
>
>
> El domingo, 15 de noviembre de 2015, 17:35:45 (UTC-6), Steven G. Johnson
> escribió:
>>
>> function prealloc(n)
>> a = Array(Int, n)
>> for i = 1:n
>> a[i] = i
>> end
>> return a
>> end
>> function dynamic(n)
>> a = Int[]
>> for i = 1:n
>> push!(a, i)
>> end
>> return a
>> end
>> @time prealloc(10^7);
>> @time dynamic(10^7);
>>
>>
>> On my machine, the preallocated version is 2.5–3x faster. A significant
>> but not overwhelming margin.
>>
>
> However, if you are doing actual calculations inside the loop
> (rather than just storing the values), then in my experience the
> performance difference is much smaller.
>
For example,
function prealloc2(n)
a = Array(Float64, n)
for i = 1:n
a[i] = sqrt(i)
end
return a
end
function dynamic2(n)
a = Float64[]
for i = 1:n
push!(a, sqrt(i))
end
return a
end
prealloc2(1)
dynamic2(1)
N = 10^8
@time prealloc2(N);
@time dynamic2(N);
0.973452 seconds (6 allocations: 762.940 MB, 15.12% gc time)
1.042340 seconds (33 allocations: 912.361 MB, 8.61% gc time)
>
>