total = 0
n = 1e6
@time for i in 1:n
global total += i
end 0.420505 seconds (4.02 M allocations: 77.056 MiB, 4.61% compilation time)
Marie-Hélène Burle
In this section, we cover an important point when it comes to Julia and performance: you should avoid global variables (that is, avoid variables defined in the global environment) as much as possible.
Scope of variables: Environment within which a variables exist
Global scope: Global environment of a module
Local scope: Environment within a function, a loop, a struct, a macro, etc.
The Julia compiler is not good at optimizing code using global variables. Part of the reason is that their type can change.
We will use the @time macro to time a loop:
0.420505 seconds (4.02 M allocations: 77.056 MiB, 4.61% compilation time)
Note the garbage collection (gc) time: 14% of total time.
Garbage collection time is a sign of poor code.
0.025860 seconds (2.00 M allocations: 30.518 MiB)
We get a 7.5 speedup.
The memory allocation also decreased by more than half.
For more accurate performance measurements, you should use the @btime macro from the BenchmarkTools package which excludes compilation time from the timing, averages metrics over multiple runs, and is highly customizable.