I need help about constructing functions inside functions that use variables that “seems” global:
function a()
aux = Float64[]
b = ()->begin
push!(aux, rand())
end
b()
b()
return aux
end
julia> a()
I know that are other (possibly better) ways to do that, but using those variables inside those functions like they were globals will make my life very easy. Question: is there any performance penalty in this case? Where can I read more about this use case?
There seems to be a small overhead comparing the two versions below. You may not need to deal with it unless you really want to optimize the code to the fullest extent.
function a1()
aux = Float64[]
b = ()->begin
push!(aux, rand())
end
b()
b()
return aux
end
function a2()
b! = (aux)->begin
push!(aux, rand())
end
aux = Float64[]
b!(aux)
b!(aux)
return aux
end
using BenchmarkTools
@btime a1(); # 102.432 ns (3 allocations: 144 bytes)
@btime a2(); # 96.532 ns (2 allocations: 128 bytes)