Why is inplace addition to array slice allocating?

I found an allocation in my code I wasn’t expecting. It happens when I do inplace addition .+= to a slice of an array. Consider the following:

foo = zeros(3,3,3)

function test1(foo)
    foo[1,:,1] .+= 2
    return nothing
end
function test2(foo)
    @views foo[1,:,1] .+= 2
    return nothing
end

@time test1(foo) # 0.000006 seconds (1 allocation: 80 bytes)
@time test2(foo) # 0.000006 seconds

So obviously this is pretty low-stakes, since the @views macro fixes it. But I’m curious: why does this happen? Is it safe to use @views here?

I think it is because

foo[1,:,1] .+= 2

expands to

foo[1,:,1] .= foo[1,:,1] .+ 2

so a copy of the slice is assigned.
see: Allocation when assigning to a slice

2 Likes

Aha, interesting. Thanks!