Question about allocations and generators

Note that all allocations come from not knowing the size of the output at compile time. If the size of the static vector to be created is known at compile time, the function does not allocate. This can be shown here, for example, in this case, where the size of the output is provided as a parameter of the type, even if the actual vector that the type contains is not static:

julia> struct Vec{N}
         v::Vector{Int}
       end

julia> g4(v::Vec{N}) where N = SVector{N,Int}(v.v[i] for i in 1:N)
g4 (generic function with 1 method)

julia> @btime g4(v) setup=(v=Vec{3}(rand(Int,3)))
  2.189 ns (0 allocations: 0 bytes)

(which means, more generally, that creating static vectors generally does not allocate if you can provide to the function where the allocations occur the size of the vectors as one parameter of the input types).

3 Likes