Is it possible to re-write the following function foo(x, y)
, such that it only uses one allocation?
using BenchmarkTools
function foo(x::Vector{Float64}, y::Vector{Float64})
(x .- y) .* 3.0
end
This currently yields 3 allocations:
julia> @btime foo([1.0, 1.0, 1.0], [2.0, 2.0, 2.0])
57.477 ns (3 allocations: 336 bytes)
3-element Vector{Float64}:
-3.0
-3.0
-3.0
Is it possible to get this down to one allocation with 112 bytes, as one would get with allocating an array of length 3? For instance:
function give_me_array_please()
[0.0, 0.0, 0.0]
end
yields:
julia> @btime give_me_array_please()
16.934 ns (1 allocation: 112 bytes)
3-element Vector{Float64}:
0.0
0.0
0.0