# Memory allocation in type construction

**URL:** <https://discourse.julialang.org/t/memory-allocation-in-type-construction/14821>\
**Category:** Performance\
**Created:** [September 11, 2018, 6:15pm UTC](https://discourse.julialang.org/t/memory-allocation-in-type-construction/14821 "2018-09-11T18:15:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![retrosnub](https://avatars.discourse-cdn.com/v4/letter/r/ecb155/32.png) [@retrosnub](https://discourse.julialang.org/u/retrosnub)\
**Post date:** [September 11, 2018, 6:15pm UTC](https://discourse.julialang.org/t/memory-allocation-in-type-construction/14821/1 "2018-09-11T18:15:15Z")

</div>

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

```julia
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.

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [September 11, 2018, 7:25pm UTC](https://discourse.julialang.org/t/memory-allocation-in-type-construction/14821/2 "2018-09-11T19:25:34Z")

</div>

> [@retrosnub](#):
>
> A thin wrapper like `A` shouldn’t allocate anything at all on the heap.

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

---

<div class="post-metadata">

**Author:** ![retrosnub](https://avatars.discourse-cdn.com/v4/letter/r/ecb155/32.png) [@retrosnub](https://discourse.julialang.org/u/retrosnub)\
**Post date:** [September 11, 2018, 7:58pm UTC](https://discourse.julialang.org/t/memory-allocation-in-type-construction/14821/3 "2018-09-11T19:58:39Z")

</div>

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)
