I’m having trouble finding the best way to include data in a module. Basically I have a small array (5 x 5) of constant data, but to interface with other packages, I want to define a function that just returns the element in the constant array at a given index.
From what I can tell, defining a constant array in the global scope of the module isn’t possible. Is that right? Is the best way to just define the data as a normal global array and then reference it inside my function? I can’t think of any other way to avoid having an array in the global scope of the module.
I ran some mini-benchmarks and it looks way more expensive to define the array inside the function (not surprisingly). Is there a better way to include constant data in a module than using a globally defined array?
Here’s a minimal working example that shows the difference between the global and local approach, with some quick
using BenchmarkTools # data defined globally data_outer = [1.0 2.0; 3.0 4.0] f_outer(x,y) = data_outer[x, y] # data redefined inside function function f_inner(x,y) data_inner = [1.0 2.0; 3.0 4.0] data_inner[x, y] end # large data defined globally data_outer_large = rand(1_000, 1_000) f_outer_large(x,y) = data_outer_large[x, y] # large data redefined inside function function f_inner_large(x,y) data_inner_large = rand(1_000, 1_000) data_inner_large[x, y] end
julia> @btime f_outer(1,2) 26.666 ns (1 allocation: 16 bytes) 2.0 julia> @btime f_inner(1,2) 41.318 ns (1 allocation: 112 bytes) 2.0 julia> @btime f_outer_large(1,2) 28.890 ns (1 allocation: 16 bytes) 0.6037250079523222 julia> @btime f_inner_large(1,2) 4.157 ms (2 allocations: 7.63 MiB) 0.36772602420929323