Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

skip unnecessary alias-check in collect(::AbstractArray) from copyto! #55748

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

thchr
Copy link
Contributor

@thchr thchr commented Sep 12, 2024

As discussed on Slack with @MasonProtter & @jakobnissen, collect currently does a usually cheap - but sometimes expensive - aliasing check (via unalias->mightalias->dataid -> objectid) before copying contents over; this check is unnecessary, however, since the source array is newly created and cannot possibly alias the input.
This PR fixes that by swapping from copyto! to copyto_unaliased! in the _collect_indices implementations where the swap is straightforward (e.g., it is not so straightforward for the fallback _collect_indices(indsA, A), so I skipped it there).

This improves the following example substantially:

struct GarbageVector{N} <: AbstractVector{Int}
    v :: Vector{Int}
    garbage :: NTuple{N, Int}
end
GarbageVector{N}(v::Vector{Int}) where N = GarbageVector{N}(v, ntuple(identity, Val(N)))
Base.getindex(gv::GarbageVector, i::Int) = gv.v[i]
Base.size(gv::GarbageVector) = size(gv.v)

using BenchmarkTools
v = rand(Int, 10)
gv = GarbageVector{100}(v)
@btime collect($v);  # 30 ns (v1.10.4)  -> 30 ns (PR)
@btime collect($gv); # 179 ns (v1.10.4) -> 30 ns (PR)

Relatedly, it seems the fact that mightalias is comparing immutable contents as well - and hence slowing down the unalias check for the above GarbageVector via a slow objectid on tuples - is suboptimal. I don't know how to fix that though, so I'd like to leave that outside this PR. (Probably related to #26237)

@thchr thchr changed the title speed up collect(::AbstractArray) by skipping unnecessary alias-check in copyto! skip unnecessary alias-check in collect(::AbstractArray) from copyto! Sep 12, 2024
@thchr
Copy link
Contributor Author

thchr commented Sep 23, 2024

Bump.

@giordano giordano added performance Must go faster arrays [a, r, r, a, y, s] labels Sep 23, 2024
@thchr
Copy link
Contributor Author

thchr commented Oct 11, 2024

Bump; I think this is not likely to be very controversial.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
arrays [a, r, r, a, y, s] performance Must go faster
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants