# Loop over array of static arrays

**URL:** <https://discourse.julialang.org/t/loop-over-array-of-static-arrays/121769>\
**Category:** Performance\
**Tags:** question, staticarrays\
**Created:** [October 26, 2024, 1:16am UTC](https://discourse.julialang.org/t/loop-over-array-of-static-arrays/121769 "2024-10-26T01:16:20Z")\
**Posts on this page:** 1\
**Showing post:** 2

<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:** [October 26, 2024, 1:32am UTC](https://discourse.julialang.org/t/loop-over-array-of-static-arrays/121769/2 "2024-10-26T01:32:27Z")

</div>

> [@nicolas](#):
>
> I was wondering whether I could accelerate this using static arrays.

Yup. The following is about 7x faster for me:

```julia
function doubles_using_sarrays()
    xs = [@SVector(ones(10)) for i in 1:10]
    for i in 1:9
        xs[i+1] = double(xs[i])
        # Do some more stuff
    end
    xs
end

```

Key points:

1. Don’t call `ones(10)` and _then_ convert to a StaticArray. Not only does this first heap-allocate a `ones(10)` array before converting, but it is also **type-unstable**. The key to efficient use of StaticArrays is to **let the compiler know the length of the array**. The `@SVector` macro rewrites the `ones(10)` into a call to `StaticArrays.ones((SVector){10})`, which puts the length `10` in the type. — this is a common confusion, see e.g. [Optimizing function with vector reassignments - #8 by stevengj](https://discourse.julialang.org/t/optimizing-function-with-vector-reassignments/120938/8)
2. Since `SVector` is immutable, use `=` instead of `.=`.

(The only remaining heap allocation is the container `xs`. You could use a static array for that as well, if you want, but as the size of the object increases the advantage of static arrays is less. And, again, you only get an advantage if you know the length at compile time. Does it really make sense in your application to make the length a constant?)

---

_[View the full topic](https://discourse.julialang.org/t/loop-over-array-of-static-arrays/121769)._
