I’m writing some program which for the sake of aesthetics manipulates data as SMatrix{2,2, Float64}. However, I noticed that, having a collection of such SMatrices, say in variable Ms
, the command sum(Ms)
allocates memory. Insdeed,
using StaticArrays
Ms = Vector{SMatrix{2, 2, Float64}}();
for i in 1:1000
push!(Ms, SMatrix{2, 2, Float64}(rand(2,2)))
end
@time sum(Ms)
# 0.000053 seconds (999 allocations: 46.828 KiB)
isconcretetype(SMatrix{2,2,Float64})
# false
Indeed, calling @code_warntype sum(Ms)
produces
MethodInstance for sum(::Vector{SMatrix{2, 2, Float64}})
from sum(a::AbstractArray; dims, kw...) @ Base reducedim.jl:994
Arguments
#self#::Core.Const(sum)
a::Vector{SMatrix{2, 2, Float64}}
Body::Any
1 ─ nothing
│ %2 = Base.:(:)::Core.Const(Colon())
│ %3 = Core.NamedTuple()::Core.Const(NamedTuple())
│ %4 = Base.pairs(%3)::Core.Const(Base.Pairs{Symbol, Union{}, Tuple{}, NamedTuple{(), Tuple{}}}())
│ %5 = Base.:(var"#sum#807")(%2, %4, #self#, a)::Any
└── return %5
showing an errant Any
. Surely this is not the intended behavior of StaticArrays
? Is there a workaround?