Why does using structs increase allocations (and calculation time)

This is creating containers with abstract types unfortunately. Dealing with abstract types require heap allocations (as you don’t know how much memory is need ahead of time). You could do:

struct single_HOI_ecosystem{T<:Real} <: one_HOI_ecosystem
    N::Int
    n::Vector{T}
    m::Matrix{Float64}
    A::Matrix{Float64}
    R::Vector{T}
    d::Vector{T}
end

Modifying if you need some more types. The general rule of thumb is that the types should be either concrete in the struct or have a parametric type which should also be concrete. You should check what T is when creating the struct to make sure it is concrete.

Also, use @code_typed to check for type instabilities , Unions, Anys or abstract types that can’t be inferred.

7 Likes