Unwanted allocations calling function stored in structure

Below is a toy example of my problem. The call b.f(1.0) allocates memory. Is it possible to call the function h inside FunctionHolder without allocations?

struct FunctionHolder
    f :: Function
end

function main()
    g(x) = x+1
    a = FunctionHolder(g)
    @time g(1)
    @time a.f(1)

    h(x) = x+1.0
    b = FunctionHolder(h)
    @time h(1.0)
    @time b.f(1.0)  # why allocation here?
end

main()
main()

Produces the following output.

0.000000 seconds
0.001330 seconds (11 allocations: 880 bytes)
0.000000 seconds
0.001294 seconds (13 allocations: 992 bytes)
0.000000 seconds
0.000001 seconds
0.000000 seconds
0.000001 seconds (1 allocation: 16 bytes)

This is expected. Function is an abstract type. This is the same issue as always with a field of an abstract type. For strict typing,

struct FunctionHolder{F}
    f :: F
end
1 Like

Thank you!