Are broadcast-assignment and `copyto!` safe with aliasing?

goerz
Wed, 20 Mar 2024 21:03:10 +0000
New to Julia

Are broadcast-assignment and copyto! between two AbstractVector objects guaranteed to be safe if the two vectors alias each other (in a non-crazy way)? I’m especially interested if copying from an array into itself is guaranteed to be a no-op:

a .= a
copyto!(a, a)

Or do I have to prefix that with an explicit check?

if a !== b
    copyto(a, b)
end

Would the compiler be able to figure out that copyto!(a, a) is exactly a no-op? That is, should I use the check in my code for performance reasons, even if the copyto! itself is safe?

In my application, I probably don’t need other types of aliasing than the vectors being identical, so anything beyond that is more of a curiosity. I’m definitely not interested in “crazy” aliasing, e.g. if b is an AbstractVector that is some permuted view of a. I think what I’m asking is whether I can assume that broadcast-assignment and copyto! work equivalently to

function copyto!(a, b)
    for i in eachindex(b)
        a[i] = b[i]
    end
end

(ignoring that a and b might have different indices; you get the point).

2 posts - 2 participants