Number of allocations

I have difficulties understanding the number of allocations. In the following:

const v1 = [0, 1]
const v2 = [1, 2]

fun1(x) = begin
    a = x .+ v1
    return a .* v2
end

fun2(x) = @. (x + v1) * v2

julia> @btime fun1([10, 20]);
  102.232 ns (3 allocations: 288 bytes)

julia> @btime fun2([10, 20]);
  69.386 ns (2 allocations: 192 bytes)

for fun1(), one allocation for a + one allocation for output, so I think there should be 2 allocations, but in fact there’re 3.
for fun2(), only one allocation is needed for output, but in fact there’re 2 allocations.

where is the extra allocation? thanks

Here’s a hint:

julia> @btime [10, 20]
  30.892 ns (1 allocation: 96 bytes)
2-element Array{Int64,1}:
 10
 20

spoiler alert:

You’re allocating memory just by passing the input array. If you don’t want to count that allocation, you need to interpolate the argument into the benchmark macro:

julia> @btime fun1($([10, 20]));
  74.942 ns (2 allocations: 192 bytes)

julia> @btime fun2($([10, 20]));
  41.787 ns (1 allocation: 96 bytes)
9 Likes