Hello,
I am trying to understand why the calling of a relatively simple method with unused type parameters allocates memory, while the same method with no type parameters does not.
I have a method that is aiming at computing a Gramian matrix from a vector basis. The methods has three arguments: two singleton types and one matrix. I am giving here below a simplify version of this method:
using BenchmarkTools
struct TVar1 end
struct TVar2 end
struct TVec{Var, Sign} end
function foo(arg1::TVec{Var1, Sign1}, arg2::TVec{Var2, Sign2}, gram_matrix) where {Var1, Sign1, Var2, Sign2}
gram_matrix[1, 2] = 20.
end
function dummy_assignment(M)
gram_matrix = Array{Float64, 2}(undef, 2, 2)
fill!(gram_matrix, 0.1)
basis = [TVec{TVar1(), 1}(); TVec{TVar2(), -1}()]
for k = 1:M
for i = 1:length(basis)
for j = 1:length(basis)
foo(basis[i], basis[j], gram_matrix)
end
end
end
end
Launching a time benchmark:
@btime dummy_assignment(10000)
gives me: 937.600 μs (40002 allocations: 625.20 KiB)
If, from the method I am deleting the unused type parameters:
function foo(arg1::TVec, arg2::TVec, gram_matrix)
gram_matrix[1, 2] = 20.
end
the same time benchmarking gives: 75.200 μs (2 allocations: 208 bytes)
I’ve also checked the method with @code_warntype for possible type instabilities but everything seems to be ok.
Could you please help me understand why Julia is allocating memory in this particular case?
Thank you for your help.
Kind regards,
Alexandru