I have some code that allocates on the heap (and shouldn’t) while constructing a StaticArray
. The hunt leads me to this MWE:
using StaticArrays, BenchmarkTools
@btime SVector{4,Float64}(2. *i for i=1:4) # good, no allocation
@btime ntuple(i->2. *i,4) # good too, no allocation
v = SVector{4,Float64}(1.,2.,3.,4.)
@btime SVector{4,Float64}(v[i] for i=1:4) # but why does this allocate?
@btime ntuple(i->v[i],4) # and this too?
Why does accessing an array element allocate? To check that this is not a measurement artifact, I package the allocating code in a on-liner function and @btime 'd it.
Of course the above MVE is nonsensical - I could just copy v
. Nonsensical or not, I do not understand what causes the allocation, and understanding this would probably help me correct my real code.
NB: I’m still on Julia 1.9, for no good reason… Is that an issue here?