Skip to content

copyto! sometimes copies whole source array when there is possibility of aliasing #50900

Open
@LilithHafner

Description

@LilithHafner
julia> using OffsetArrays, BenchmarkTools

julia> function _copyto!(dest, desto, src, srco, n)
           for i in 0:n-1
               dest[i + desto] = src[i + srco]
           end
           dest
       end
_copyto! (generic function with 1 method)

julia> x = rand(100_000);

julia> y = OffsetArray(x, 0);

julia> @btime copyto!(x, 20, x, 10, 5);
  20.728 ns (0 allocations: 0 bytes)

julia> @btime _copyto!(x, 20, x, 10, 5);
  18.036 ns (0 allocations: 0 bytes)

julia> @btime copyto!(y, 20, y, 10, 5);
  11.875 μs (2 allocations: 781.30 KiB) # That's microseconds, not nanoseconds!

julia> @btime _copyto!(y, 20, y, 10, 5);
  17.827 ns (0 allocations: 0 bytes)

The issue is that unaliasing checks for possible aliasing, and if present copies the entire source array. This causes major performance losses here. It can also cause bugs when reading from an array has side effects (this is responsible for a test failure in JuliaCollections/SortingAlgorithms.jl#71)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugIndicates an unexpected problem or unintended behaviorperformanceMust go faster

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions