Julia in-place modification and memory usages

The problem with global variables is that the compiler cannot be sure that their type does not change. Therefore, they need to be “boxed”, i.e. their type must be checked at run-time for each operation on them. If they are used in tight loops, this could easily result in a performance loss of a factor 100.
Putting them into a module does not help if they are still (module-level) globals.
To avoid the performance penalty, you could either declare the globals as const or pass them as function arguments. For a large number of variables, you could either use NamedTuples (as @mcabbott suggested) or a custom struct.
For the latter, you can define default values using Base.@kwdef.
When defining a struct, make sure to use concrete or parametric types, not abstract types for the same performance reasons as described above.

2 Likes

If the global variables are constant, I.e. you never need to change them, you can mark them as constant, like const x = 1. This thing won’t have any performance impact inside functions.

1 Like