Julia hangs while displaying an SMatrix

The following code hangs on Windows 10 and Julia 1.5.0 on two different computers:

using StaticArrays

struct Points{N,T<:Number}
    p::SMatrix{3,N,T}
end
Points(x::Matrix{T}) where {T} = Points{size(x,2),T}(x)

points = Points(randn(3,2000))
points.p

points = Points(randn(3,1000)); points.p is slow but returns.

Am I doing something wrong?

From the StaticArrays manual:

Note that in the current implementation, working with large StaticArrays puts a lot of stress on the compiler, and becomes slower than Base.Array as the size increases. A very rough rule of thumb is that you should consider using a normal Array for arrays larger than 100 elements.

A static array with 6000 elements is waaaaaaay too large. You’re essentially creating a 6000-element tuple, and the compiler is really struggling.

At least in the example you’ve given, there’s no reason at all to use an SMatrix for this. A plain Matrix{T} or a Vector{SVector{3, T}} would both work well and would not stress the compiler at all.

6 Likes

StaticArrays aren’t a panacea that you should drop into every array computation to make them faster.

They are useful for tiny arrays (e.g. coordinate-vectors in 3d geometry) where the overhead of allocating arrays or even just looping is comparable to the cost of elementary array operations like vector + vector. For large arrays this overhead is relatively unimportant, especially if you do in-place operations, and the costs of StaticArrays (e.g. in compile time and instruction-cache overutilization) outweigh the benefits.

4 Likes

https://github.com/mateuszbaran/HybridArrays.jl is designed exactly for the case of some dimensions being small and some being large. It’s much more convenient than Vector{SVector{3, T}}.

4 Likes