Question About @allocated

I am observing some behavior and I don’t understand it. I would appreciate any thoughts. For context, I’m using VSCode with the Julia extension, interactively evaluating each line of my code by highlighting it and pressing Shift+Enter.

This is the code.

A = rand(10)
B = rand(10)
C = rand(10)
D = zeros(Float64, 10)

function test_alloc(A, B, C, D)
    for j = 1:length(A)
        D[j] = B[j] * C[j]
    end
    sum!(A, D)
end

My expectation is that I will get zero heap allocations from this since no new arrays are created inside the function and no slices or views are made.

I check the allocation by doing a = @allocated test_alloc(A, B, C, D) and it tells me 1123001 bytes(?) were allocated. I then evaluate the line a = @allocated test_alloc(A, B, C, D) again, without changing anything, and it says 0 bytes. I’m wondering, why does it change when I evaluate it the second time?

I also note that when I do @btime test_alloc($A, $B, $C, $D) the result is 0 allocations as I expect.

It compiles the first time.
Compilation allocates.

1 Like

Thanks - that helped. I also found this post which filled in the remaining gaps I had.