I'm using a julia script where I've defined two functions that need to share variables. What is the best practice for doing this? Should I just use global variables or is there a julia-specfic workaround that I can use instead?
I'm using a julia script where I've defined two functions that need to share variables. What is the best practice for doing this? Should I just use global variables or is there a julia-specfic workaround that I can use instead?
Normally you would pass around the variable to both functions as Benoit suggested.
However, if you need to avoid it for some reason, this is often the case e.g. when passing a function to an optimization routine that should depend on some external parameter, then use a closure instead of using a global variable. In general non-const global variables should be avoided in Julia for performance reasons.
Here is an example:
No closure:
julia> using Optim, BenchmarkTools
julia> c = 10
10
julia> f(x) = (x-c)^2
f (generic function with 1 method)
julia> @btime optimize(f, -100, 100);
5.500 μs (235 allocations: 3.81 KiB)
Now the same with closure. First I use let:
julia> @btime let c = 10
f(x) = (x-c)^2
optimize(f, -100, 100)
end;
139.605 ns (2 allocations: 176 bytes)
You can also use a function:
julia> function wrap()
c = 10
f(x) = (x-c)^2
optimize(f, -100, 100)
end
wrap (generic function with 1 method)
julia> @btime wrap();
139.100 ns (2 allocations: 176 bytes)
Also if c were a const things would be also fast (start a fresh Julia session for this):
julia> using Optim, BenchmarkTools
julia> const c = 10
10
julia> f(x) = (x-c)^2
f (generic function with 1 method)
julia> @btime optimize(f, -100, 100);
138.603 ns (2 allocations: 176 bytes)