Functions inside functions using "global" variables

Hi!

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?

You’re making a closure, which is a very acceptable thing to do (unless I misunderstand your example). Closures are preformant, except for one bug in Julia: performance of captured variables in closures · Issue #15276 · JuliaLang/julia · GitHub

There was a recent thread discussing work-arounds: Avoiding Allocations with User provided Closures

3 Likes

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)
1 Like