Allocation with Subset of Matrix and Views


I’m wondering if anyone can help me understand the following. I want to replace a subset of matrix A with matrix B. I understand this can be done efficiently using for loops or copyto!. I am specifically interested in the behavior of the following case.

The following does not allocate.

A = zeros(5, 5)
B = ones(3, 3) * 2
function viewtest!(A, B)
    tmp = @view A[2:4, 2:4]
    tmp .= B
    return nothing
@allocated viewtest!(A, B) # 0

This function does allocate.

function broadcasttest!(A, B)
    A[2:4, 2:4] .= B
@allocated broadcasttest!(A, B) # 64

I think in broadcasttest! the code A[2:4, 2:4] means I am creating a slice of an array which is going to allocate? Is that why? My initial expectation was this would also have zero allocation because it is an inplace operation (I think) reflected by the .=

EDIT: see the following post - there may not have been any deeper issue here.

There’s definitely something unfortunate happening here and it could probably be better. It’s an interaction of the left-hand slice and .=. But

function broadcasttest!(A, B)
    A[2:4, 2:4] = B # not .=
@allocated broadcasttest!(A, B) # 0

does what you want if you don’t need the broadcasting to expand singleton dimensions.

Actually I think I did something stupid here. return nothing was missing from broadcasttest!