How to define Parameters locally in Sub julia files?

Below is just an MWE for the concept (I am using dummy equations).
I have main code in mani.jl which includes another file subi.jl. The main code calls function ini(args) to calculate mat which is useful only in function update (located in subi.jl).
Since update is being called within for loop and transferring the argument mat at each iteration could be costly (when it is very big). So, is there a way to let ini() creates and defines mat only inside the file subi.jl (maybe by adding some lines), so I can then call only by two arguments, i.e., update(R,i)

###################### subi.jl ######################
using SparseArrays, LinearAlgebra

function ini(data)
       mat = sparse(1:length(data), [4,6,7,7,8,9], d);
       mat;
end

function update(R,mat,i)
       R .+= mat .* i;
end

###################### maini.jl ######################
using SparseArrays, LinearAlgebra
include("subi.jl");
d = [10,20,30,40,50,60];
mat = ini(d)
R = copy(mat);

function run(mat,R)
       for i in 1:100
              update(R,mat,i)
       end
end

run(mat,R);

Julia passes non-isbits values (like sparse arrays) by reference, not by value, so no real cost is incurred by passing mat as an argument. Is your concern only conceptual, or have you seen some performance deficit when benchmarking?

1 Like

Thanks for your comment.
It is only conceptual as I thought it will transfer the arguments which will consumes time.

As an example, let’s try a function that randomly selects an element from an array and calculates its square root:

julia> f(x) = sqrt(rand(x))
f (generic function with 1 method)

It takes basically the same amount of time for arrays of either 3 or 30,000 elements:

julia> @btime f(v) setup = (v = rand(3));
  13.500 ns (0 allocations: 0 bytes)

julia> @btime f(v) setup = (v = rand(30_000));
  14.729 ns (0 allocations: 0 bytes)
2 Likes

Am, maybe the case of 30000 elements will be always slower?

Well, it’s 10% slower (probably due to cache behavior), not 10,000 times slower. Hopefully that’s enough to demonstrate that Julia is passing the array by reference.

1 Like