Performance

Author

Marie-Hélène Burle

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

This means: avoid variables defined in the global environment.

Definitions

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.

Example

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
end
  0.364778 seconds (4.00 M allocations: 76.360 MiB, 64.25% gc time, 4.36% 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
    end
end

local_loop(0, 1e6)
  0.026919 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.