Using module variables in a module function. Is there a performance disadvantage?

module A

b = "test"

function crazy_use_of_b_1() 
    #... using A.b 
end

function crazy_use_of_b_2(;_b = A.b) 
    #... using _b 
end

end

Is there a performance difference from 1 to 2. Or problems with type stability? Which one of the two are better?

You will be running into

https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-global-variables-1

here, unrelated to modules. If you fix that, A.b will be fine, though unnecessary within A.

Using global constants is not crazy at all, it is part of your programmer’s toolbox.

2 Likes

That’s a need trick.

global x = rand(1000)

function loop_over_global()
    s = 0.0
    for i in x::Vector{Float64}
        s += i
    end
    return s
end

So the code above would be as good as

global x = rand(1000)

function loop_over_global(_x::Vector{Float64})
    s = zero(eltype(_x))
    for i in _x
        s += i
    end
    return s
end

I would do

const x = rand(1000)

If possible. Using this will be type stable.

3 Likes

Are you sure you want s = zero(eltype(x)) and not s = zero(eltype(_x))?

1 Like