Unwanted allocations calling function stored in structure


#1

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)

#2

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

#3

Thank you!