Why does SMatrix allocate in this case?

Hello everyone,

Suppose I have:

using StaticArrays

using Chairmarks


N 		   = 10
Dimensions = 2
DimensionsPlus = Dimensions + 1
FloatType  = Float64


SVectors = rand(SVector{DimensionsPlus, FloatType}, N)
MVectors = rand(SMatrix{DimensionsPlus, DimensionsPlus, FloatType}, N)


function UpdateVectors(Vectors)
	tmp = rand(eltype(Vectors))
	for i in eachindex(Vectors)
		Vectors[i] += Vectors[i]
	end
end


@b UpdateSVector($SVectors)
@b UpdateSVector($MVectors)

Running this code gives:

julia> @b UpdateSVector($SVectors)
7.061 ns

julia> @b UpdateSVector($MVectors)
479.167 ns (20 allocs: 1.562 KiB)

In theory, everything is known at compile time as far as I know? If I split the SMatrix into 3 different SVectors, then I would get zero allocs. Is there a way I can get the SMatrix to work with zero allocations or a way to make a “view” using multiple vectors of SVector to represent a 3x3 matrix?

Kind regards

The SMatrix type is abstract, you’re missing the last type parameter that is the total length. Try this instead SMatrix{DimensionsPlus, DimensionsPlus, FloatType, DimensionsPlus*DimensionsPlus}

2 Likes

I confirm, thanks a lot!

#Working code, some mistakes in post

using StaticArrays

using Chairmarks


N 		   = 10
Dimensions = 2
DimensionsPlus = Dimensions + 1
FloatType  = Float64


SVectors = rand(SVector{DimensionsPlus, FloatType}, N)
MVectors = rand(SMatrix{DimensionsPlus, DimensionsPlus, FloatType, DimensionsPlus*DimensionsPlus}, N)


function UpdateVectors(Vectors)
	tmp = rand(eltype(Vectors))
	for i in eachindex(Vectors)
		Vectors[i] += Vectors[i]
	end
end


@b UpdateVectors($SVectors)
@b UpdateVectors($MVectors)

It seems that this shouldn’t be necessary. New issue opened `zeros`, `rand`, `randn` could infer the length parameter of incompletely parameterized `StaticArray`s · Issue #1303 · JuliaArrays/StaticArrays.jl · GitHub.

1 Like