Speed difference when storing annonymous function in variable vs. function

Apologies if I am making a mistake with my benchmarking here, but I am wondering why there is such a significant speed difference between using an annonymous function stored in a variable vs. stored in a function, as in the MWE below:

function new_anon()
    f(a) = a -> (a^(a-1))/a
end

test1 = new_anon()
test2(x) = new_anon()(x)

@btime test1(5) # 20.190 ns (0 allocations: 0 bytes)
@btime test2(5) # 0.001 ns (0 allocations: 0 bytes)

Because test1 is a non-const global variable (while test2 is a function).

5 Likes

Thanks, I updated my benchmarks appropriately with the const prefix and they are now equal to each other.