Efficiently passing a set of constants to a function

Maybe I’m understanding it wrong but you mean that the significant size of the constants set should be up to 100 approximately to consider using a struct this way?

If it is okay using it this way for a small constant set then could it be passed several times throughout the functions of a module without a severe speed or memory penalty?

For example, if the functions do different things but do need those constants for different computations:

mutable struc Constants
    ...
end

function compute_this(x, params=Constants() )
    ...
end

function compute_that(x, y, params=Constants() )
    ...
end

# more functions below ...

The largest number of constraints should be roughly that one. But I’m not thinking of the case in which you are repeatedly creating a new instance of the structure, in independent functions.

I’m thinking more on the case where you have nested function calls and the parameters are passed around.

In this case, a small immutable struct is a good option. If the number of parameters is too large you will end having to use a heap allocated object (an array, a dict, etc), and then it may be better for performance to copy the constants that are used in each local scope to avoid unnecessary getindex calls.

1 Like