Marie-Hélène Burle

The one thing you need to remember: avoid global variables.

This means: avoid variables defined in the global environment.


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.

Why avoid global variables?

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:

  • In the global environment:
total = 0
n = 1e6

@time for i in 1:n
    global total += i
  0.640359 seconds (4.00 M allocations: 76.360 MiB, 77.50% gc time, 2.08% compilation time)

Note the garbage collection (gc) time: 14% of total time.

Garbage collection time is a sign of poor code.

  • In a local environment (a function):
function local_loop(total, n)
    total = total
    @time for i in 1:n
        global total += i

local_loop(0, 1e6)
  0.033492 seconds (2.00 M allocations: 30.518 MiB, 18.12% gc time)

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.