Yup. The following is about 7x faster for me:
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:
- Don’t call
ones(10)
and then convert to a StaticArray. Not only does this first heap-allocate aones(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 theones(10)
into a call toStaticArrays.ones((SVector){10})
, which puts the length10
in the type. — this is a common confusion, see e.g. Optimizing function with vector reassignments - #8 by stevengj - 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?)