Allocation by StaticArrays in anonymous function/macro

The following code produces 1 allocation of 32 bytes if the function is created by a macro (same effect if it were an anonymous function). It has 0 allocations if the function is not created by a macro. Note that the allocation goes away if foo() does something that does not require StaticArrays (such as just return 1.0). Can someone tell me what is causing this allocation, and how I can get rid of it?


macro myfunction()
    quote
        function foo()
            return @SVector Float64[1.0, 2.0]
        end
    end
end

l = @myfunction
@btime l()

function foo()
    return @SVector Float64[1,1]
end

@btime foo()

Your l is a non-constant global variable, so you need to interpolate it into the benchmark: @btime ($l)() (see: https://github.com/JuliaCI/BenchmarkTools.jl#quick-start)

2 Likes

that makes sense, thanks!