I’m distributing entries of a Tuple to the ith entry of each array in a Tuple of Arrays.
using BenchmarkTools
N = 3
X = (zeros(N),zeros(N))
Y = [1,2]
function foo1!(X,Y,i)
for fld in eachindex(X)
X[fld][i] = Y[fld]
end
end
@btime foo1!($X,$Y,$1)
foo2!(x,y,i) = x[i] = y
@btime foo2!.($X,$Y,$1)
foo3!(X,Y,i) = getindex(X,i) = Y
@btime foo3!($X,$Y,$1)
Each different approach gives a different runtimes
2.608 ns (0 allocations: 0 bytes)
44.127 ns (1 allocation: 96 bytes)
5.209 ns (1 allocation: 16 bytes)
Why is the second so slow, and is there a one-line approach which is as fast as the for loop?