# Are structs passed by value or by ref?

**URL:** <https://discourse.julialang.org/t/are-structs-passed-by-value-or-by-ref/68987>\
**Category:** New to Julia\
**Tags:** struct\
**Created:** [September 30, 2021, 10:18am UTC](https://discourse.julialang.org/t/are-structs-passed-by-value-or-by-ref/68987 "2021-09-30T10:18:27Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![gbaraldi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gbaraldi/32/22101_2.png) [@gbaraldi](https://discourse.julialang.org/u/gbaraldi)\
**Post date:** [September 30, 2021, 10:59am UTC](https://discourse.julialang.org/t/are-structs-passed-by-value-or-by-ref/68987/2 "2021-09-30T10:59:34Z")

</div>

Immutable structs are mostly stack allocated, even if it’s fields are pointers. Semantically both mutable and immutable are passed by reference, but for immutables it doesn’t really matter, since they are immutable.  
Mutable structs generally stay on the heap, and so they have slower performance, specially if you have an array of them, that is because immutable structs can be stored inline in an array, while mutable structs becomes an array of pointers.  
Other threads that went into this are interesting:

> [@Why mutable structs are allocated on the heap?](https://discourse.julialang.org/t/why-mutable-structs-are-allocated-on-the-heap/12992):
>
> From [https://docs.julialang.org/en/latest/manual/types/#Mutable-Composite-Types-1:](https://docs.julialang.org/en/latest/manual/types/#Mutable-Composite-Types-1:) In order to support mutation, such objects are generally allocated on the heap, and have stable memory addresses. If I define: mutable struct MyT x::Int end and then use MyT inside a function, such as: function f(x::Int) q = MyT(x); q.x += 1 return q.x end I would expect q to be allocated on the stack, because it is a local variable that does not change type and MyT is isbits. But it is not: @btime f(1)…

> [@Clarification about memory management of immutable and mutable struct](https://discourse.julialang.org/t/clarification-about-memory-management-of-immutable-and-mutable-struct/31064):
>
> Hello, I’ve been playing around with Julia for awhile and am a big fan of the language overall. Recently, I’ve been doing a bit of work to construct an immutable collections and functional utilities library (work in progress, but source is [here](https://github.com/noahbenson/Air.jl)). A few core pieces are finished at this point so I’ve been testing the performance. Without going into details, what I’ve found is that my persistent dictionary (PDict) has a performance on par with the Julia native Dict type, with respect to haskey, in,…

---

_[View the full topic](https://discourse.julialang.org/t/are-structs-passed-by-value-or-by-ref/68987)._
