Does declaring a variable to be constant do anything at all?

Besides the constant type which is useful for performance in the global scope, constant values do actually get inlined into functions. For example:

julia> const a = 5
5

julia> f(x) = a
f (generic function with 1 method)

julia> @code_llvm f(2.)

define i64 @julia_f_60745(double) #0 !dbg !5 {
top:
  ret i64 5
}

julia> a = 12
WARNING: redefining constant a
12

julia> @code_llvm f(3.)

define i64 @julia_f_60760(double) #0 !dbg !5 {
top:
  ret i64 5
}

Here we see that you are not getting the speedup for free. Changing the constant is allowed, but the function trusts that you won’t do this and doesn’t check the value again.

12 Likes