Unexpected Memory Allocation of Broadcasting Copy

Hi all. I encounted the problem as topic saids.

julia> a = zeros(4, 4, 3)

julia> @btime @views $a[:, :, 2] .= $a[:, :, 2]
  38.862 ns (1 allocation: 192 bytes)

julia> @btime @views for i in eachindex($a[:, :, 2])
        $a[:, :, 2][i] = $a[:, :, 2][i]
    end
  7.744 ns (0 allocations: 0 bytes)

I thought these two benchmarks do the exactly same thing.
Is this problem a bug or a specification or my wrong?
Can someone please tell me what’s going on?

I believe the allocations are occurring because @views recognises that you are assigning from a to a which refer to the same part of memory.

For example:

a = zeros(4, 4, 3)
b = zeros(4, 4, 3)
f(a, b) = (@views a[:, :, 2] .= b[:, :, 2]; return nothing)
@btime f(a, b) # no allocations
@btime f(a, a) # 1 allocation

Thank you for fast answering.

screw_dog
you are assigning from a to a which refer to the same part of memory.

I agree with you. But my second benchmark also assigns by the same way.
I wonder what the difference is.

IIRC, broadcasting can conservatively insert a copy if the source & target arrays alias, but I’m only like 85% sure on that.

Thus, this is a specification.
Thank you for answering.