Reducing getindex allocation [edit: when using an array as index]

Without a generalized MWE I can only propose

using BenchmarkTools

function get_tuple(::Val{N}, idx) where {N}
    ntuple(i -> idx[i], Val(N))
end

@btime get_tuple(Val(2), vec) setup=(vec=rand(1:2, 2))
@btime get_tuple(Val(3), vec) setup=(vec=rand(1:3, 3))
@btime get_tuple(Val(4), vec) setup=(vec=rand(1:4, 4))

const N = 2
@btime get_tuple(Val(N), vec) setup=(vec=rand(1:N, N))

@btime get_tuple(Val(M), vec) setup=(M=2; vec=rand(1:M, M))

yielding

  2.200 ns (0 allocations: 0 bytes)
  2.700 ns (0 allocations: 0 bytes)
  2.700 ns (0 allocations: 0 bytes)
  2.400 ns (0 allocations: 0 bytes)
  188.406 ns (1 allocation: 32 bytes)

showing how careful we have to be with const vs non-const (I initially tried to benchmark with the last line…).

Edit: corrected ntuple to use the Val method (which could be helpful in other situations)…

2 Likes