Allocations in construction of composite type with StaticArray field

Hello,

I’m tracking down allocations in a performance critical part of a code, where I use composite types with StaticArrays fields. I’ve noticed that initializing instances of such types triggers some allocations that I would like to eliminate (if possible).

Here is a minimal example that illustrate the issue I’m referring to.

using StaticArrays, BenchmarkTools

struct MyStaticVector{N}
    data::StaticVector{N, Int}
end

struct MyNTuple{N}
    data::NTuple{N, Int}
end

foo() = MyStaticVector(@SVector [1, 2])
bar() = MyNTuple((1, 2))

@btime foo()
@btime bar()

Running this script yields the following

$ julia alloc.jl
  9.713 ns (2 allocations: 48 bytes)
  1.452 ns (0 allocations: 0 bytes)

My understanding of statically-sized arrays is that they allow alleviating allocations altogether (do not hesitate correcting me if I’m wrong). Am I missing something?

Is there a way to rewrite foo to achieve 0 allocation? I do not know much about constructors julia, but could it be related?

Any tips will be very much appreciated. Thanks!

V.

StaticVector is an abstract type.
Try replacing it by the concrete type SVector in the type definition.

3 Likes

That did it, thanks a lot!

(Just found a related issue here.)