Convert variable vs. hardcode allocations/time

Alright, I’m sure there’s a good answer for this, but I am perplexed.

julia> using BenchmarkTools: @btime

julia> @btime convert(Float64, 5)
  0.964 ns (0 allocations: 0 bytes)
5.0

julia> a = 5
5

julia> @btime convert(Float64, a)
  102.134 ns (1 allocation: 16 bytes)
5.0

What’s happening here? Why does the second convert have any allocating and x100 slower? It didn’t help putting the convert into a function, either.

See the Performance tips in the manual. In particular, a is an untyped global.

Try @btime convert(Float64, $a) or @btime convert(Float64, a) setup=(a = $a;) instead.

Also see the BenchmarkTools.jl docs.

Alright I see now, thank you!

1 Like