Are StaticArrays always faster?

I was under the impression that StaticArrays or operations that involve SMatrix are faster than the non Static counterparts. To test this out I wrote a small code that does matrix-multiplication related computations of a Matrix and it’s SMatrix equivalent. The code is given below

using BenchmarkTools
using StaticArrays
function G_dynamic(M::Matrix{Float64})
    p = M' * M;
    q = p^2 ;
    r =p^-1;
end
function G_static(M::SMatrix)
    p = M' * M
    q = p^2 
    r =p^-1
end
M = rand(100,100)
M_static = SMatrix{100,100}(M)

@btime G_dynamic(M)

@btime G_static(M_static)

But to my surprise the G_static takes much more time than the non static counterpart. Any ideas why this is happening or under what circumstances are StaticArrays faster ?

From the README:

Note that in the current implementation, working with large StaticArray s 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.

100x100 is indeed larger than 100. Incidentally, write @btime G_dynamic($M) instead because M is an untyped global and that will spuriously introduce type instability to the benchmark loop that the normal function call won’t have past its initial dispatch.

3 Likes

I agree that 100x100 is no longer small in the context of StaticArrays.

Another point which has nothing to do with performance, but Julia‘s programming model, is that since your code is the same for the two matrix types, you could write a generic function for argument type AbstractMatrix and it would still be compiled to two different specialized methods for the two types you call it on, with no performance penalty. This is a great strength of Julia.

3 Likes