Memory allocation in type construction

I’m trying to get rid of memory allocations and reduced my problem to the following:

using BenchmarkTools
struct A{T} a::T end
a = rand(3, 3)
@btime A($a)

Does anybody know why this allocates 16 bytes and maybe how to avoid it? A thin wrapper like A shouldn’t allocate anything at all on the heap.

Note that b = 5; @btime A($b) doesn’t show any allocation.

Unless optimized away, structs containing other heap allocated objects are themselves allocated on the heap.

1 Like

Is there a reason to that? I couldn’t find a satisfactory explanation in the docs.
So there is no way of saving a stack-allocated reference to a previously created object? (Ref seems to allocate too)

2 Likes