# A nice explanation of memory stack vs. heap

**URL:** <https://discourse.julialang.org/t/a-nice-explanation-of-memory-stack-vs-heap/53915>\
**Category:** Offtopic\
**Tags:** memory-allocation\
**Created:** [January 25, 2021, 2:39pm UTC](https://discourse.julialang.org/t/a-nice-explanation-of-memory-stack-vs-heap/53915 "2021-01-25T14:39:17Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [January 29, 2021, 3:54pm UTC](https://discourse.julialang.org/t/a-nice-explanation-of-memory-stack-vs-heap/53915/12 "2021-01-29T15:54:00Z")

</div>

> [@StefanKarpinski](#):
>
> Importantly, the compiler is free to change this in either direction if it can prove that it can safely (unobservably) do so. For example, if it knows that a mutable structure doesn’t outlive the current function then it can stack allocate it. Or in the other direction, if an immutable structure is large and it would be better to heap allocate it than to pass it around on the stack then it can also do that.

And for very small data used only locally within a function, e.g. a `ComplexF64` value or a 3-component `StaticArray`, it can avoid both the heap and the stack and store the data directly in [registers](https://en.wikipedia.org/wiki/Processor_register).

Moreover, because modern CPUs typically have more physical registers than are exposed in the instruction set, with [register renaming](https://en.wikipedia.org/wiki/Register_renaming) my understanding is that the CPU itself can take a nominally stack-allocated value and store it in a register instead, e.g. to eliminate a register spill.

---

_[View the full topic](https://discourse.julialang.org/t/a-nice-explanation-of-memory-stack-vs-heap/53915)._
