Whats the difference between a regular array and an array from StaticArrays

The type of a regular Julia Array only includes the number of dimensions, not the size:

julia> typeof(Array{Int64}(3))
Array{Int64,1}

julia> typeof(Array{Int64}(10))
Array{Int64,1}

julia> typeof(Array{Int64}(1000000))
Array{Int64,1}

so the difference between a StaticArray and an Array is exactly what the docs here say: https://github.com/JuliaArrays/StaticArrays.jl , namely that the size of a StaticArray is actually part of the type:

julia> typeof(SVector(0, 0))
StaticArrays.SArray{Tuple{2},Int64,1,2}

julia> typeof(SVector(0, 0, 0))
StaticArrays.SArray{Tuple{3},Int64,1,3}

julia> typeof(SVector(0, 0, 0, 0))
StaticArrays.SArray{Tuple{4},Int64,1,4}

You would use StaticArrays when your program handles lots of small arrays (typically less than 100 elements) whose sizes are fixed or at least inferrable by the compiler. For example, if you’re storing points in 3D space, it will be much more efficient to use an SVector{3, Float64} than a regular Array{Float64} with 3 elements.

StaticArrays.jl also implements some optimized unrolled algorithms for small vectors and matrices. For example, StaticArrays.jl knows the closed-form of the matrix inverse for a 2x2 matrix:

julia> @btime inv($(rand(2, 2)))
  892.575 ns (10 allocations: 1.73 KiB)

julia> @btime inv($(rand(SMatrix{2, 2, Float64})))
  3.155 ns (0 allocations: 0 bytes)

but these optimizations are only really helpful for very small matrices. So a 2x2 or 3x3 or even 10x10 StaticArrays.SMatrix might make sense, but a 100x100 matrix is better left as a regular Julia Array.

16 Likes