Let's say we have a matrix and a vector of the indices at which we want to access that matrix:
matrix = Matrix{Float64}(undef, 5000, 4000)
point = [1244, 3353]
We can use the splat operator (...) to expand the point vector to access the matrix, or we can explicitly use point[1] and point[2] as the indices:
matrix[point...]
vs
matrix[point[1], point[2]]
The first is more elegant, but apparently also much slower:
@btime $matrix[$point...]
70.083 ns (4 allocations: 64 bytes)
@btime $matrix[$point[1], $point[2]]
1.800 ns (0 allocations: 0 bytes)
Where does this difference come from? Is there a way to make the splat operator more performant or should I simply use the other solution if I care about performance?
CodePudding user response:
Splatting a tuple seems to be the fastest of all:
julia> @btime $matrix[$point...] # point isa Array
94.484 ns (4 allocations: 64 bytes)
0.0
julia> @btime $matrix[$point[1], $point[2]] # point isa Array
2.889 ns (0 allocations: 0 bytes)
0.0
julia> @btime $matrix[$point...] # point isa Tuple
2.624 ns (0 allocations: 0 bytes)
0.0
Variadic function arguments are internally passed as tuples, so it's no surprise there is the least overhead if you directly insert a tuple.