In the following sections, we briefly go through a few techniques that can help make your Julia code run as fast as possible.
Any code that is performance critical should be inside a function. Code inside functions tends to run much faster than top level code, due to how Julia's compiler works.
The use of functions is not only important for performance: functions are more reusable and testable, and clarify what steps are being done and what their inputs and outputs are, Write functions, not just scripts is also a recommendation of Julia's Styleguide.
The functions should take arguments, instead of operating directly on global variables, see the next point.
The value of an untyped global variable might change at any point, possibly leading to a change of its type. This makes it difficult for the compiler to optimize code using global variables. This also applies to type-valued variables, i.e. type aliases on the global level. Variables should be local, or passed as arguments to functions, whenever possible.
We find that global names are frequently constants, and declaring them as such greatly improves performance:
const DEFAULT_VAL = 0
If a non-constant global is known to always be of the same type, the type should be annotated; const globals need not be annotated because their type is inferred from their initialization value.
Uses of untyped globals can be optimized by annotating their types at the point of use:
global x = rand(1000) function loop_over_global() s = 0.0 for i in x::Vector{Float64} s += i end return s end
... continue reading