# Can Julia optimize mutable static arrays to be allocated on the stack?

**URL:** https://discourse.julialang.org/t/can-julia-optimize-mutable-static-arrays-to-be-allocated-on-the-stack/66360
**Category:** General Usage
**Created:** [August 13, 2021, 8:09pm UTC](https://discourse.julialang.org/t/can-julia-optimize-mutable-static-arrays-to-be-allocated-on-the-stack/66360 "2021-08-13T20:09:01Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![Elrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elrod/32/22461_2.png) [@Elrod](https://discourse.julialang.org/u/Elrod)
#### Post date: [August 13, 2021, 8:39pm UTC](https://discourse.julialang.org/t/can-julia-optimize-mutable-static-arrays-to-be-allocated-on-the-stack/66360/2 "2021-08-13T20:39:47Z")

</div>

Yes.

```julia
julia> using StaticArrays, BenchmarkTools

julia> if VERSION >= v"1.7.0-beta"
         @inline exp_fast(x) = Base.Math.exp_impl_fast(x, Val(:ℯ))
       else
         exp_fast(x) = exp(x)
       end
exp_fast (generic function with 1 method)

julia> function alloctest(x)
         y = MVector(x)
         @inbounds @simd ivdep for i ∈ eachindex(y)
           y[i] = Base.Math.exp_impl_fast(y[i], Val(:ℯ))
         end
         s = zero(eltype(y))
         @fastmath for i ∈ eachindex(y)
           s += y[i]
         end
         s
       end
alloctest (generic function with 1 method)

julia> x = @SVector rand(32);

julia> @btime alloctest($x)
  11.995 ns (0 allocations: 0 bytes)
56.18908775961786

```

The assembly confirms that `y` is in fact stack allocated (loads and stores use `rsp`, the 64-bit-mode stack pointer).  
Note that in many cases, the `MArray` will not be allocated at all, existing only in the CPU’s registers if at all.

---

_[View the full topic](https://discourse.julialang.org/t/can-julia-optimize-mutable-static-arrays-to-be-allocated-on-the-stack/66360)._
