I was wondering if there is a way to reduce the memory allocation of a code like this:
julia> function funza(N)
a = Array{Float64}(undef,5)
b = Array{Float64}(undef,5)
for i=1:N
b = rand(5)
a = b
# println(a)
# println(b)
end
end
funza (generic function with 1 method)
I’ll try to interpret your code. Perhaps you want the function to print some random numbers? Then you can do
function funza(N)
b = Array{Float64}(undef,5)
for i in 1:N
b .= rand.() # this updates b in-place, and does not allocate anything
a = b # this does not allocate, it just puts the label a on the same vector as b
println(a)
println(b)
end
end
Now, println itself is going to create most of the allocations, there will only be a single allocation of a Float64 vector.
using Random
function funza(N)
a = Array{Float64}(undef,5)
b = Array{Float64}(undef,5)
for i=1:N
rand!(b)
a .= b
# println(a)
# println(b)
end
end
julia> @time funza(1e6)
0.022101 seconds (2 allocations: 256 bytes)
Thanks to all of you who responded. Your answers have all been great, but it’s my fault: I posted too simple code that doesn’t reflect what I’m trying to do (posting the real code here would be far too complex).
I will close the topic, and maybe I will open another one in the future in case of need.