Skip to content

[RFC] Dispatch on traits instead of types in iterate for AbstractArrays #41945

Open
@jishnub

Description

@jishnub

This is related to the issue noted in JuliaArrays/OffsetArrays.jl#257, specifically OrdinalRanges implement custom iterate methods, but AbstactArray wrappers around such ranges use the fallback iterate method for AbstractArrays. Evidently this has a significant impact on performance:

On julia 1.6.2

julia> using OffsetArrays, BenchmarkTools

julia> r = 1:1:1000; ro = OffsetArray(r); s = collect(r); so = OffsetArray(s);

julia> @btime Float64[i for i in $r];
  1.621 μs (1 allocation: 7.94 KiB)

julia> @btime Float64[i for i in $ro];
  25.306 μs (1 allocation: 7.94 KiB)

julia> @which iterate(r)
iterate(r::OrdinalRange) in Base at range.jl:670

julia> @which iterate(ro)
iterate(A::AbstractArray) in Base at abstractarray.jl:1093

julia> @btime Float64[i for i in $s];
  1.738 μs (1 allocation: 7.94 KiB)

julia> @btime Float64[i for i in $so];
  1.991 μs (1 allocation: 7.94 KiB)

Ideally iteration for the OffsetRange ro should be as fast as that for the parent range r. This might be possible using traits, if iterate dispatches on a range-like trait instead of subtypes of AbstractRange.

Another solution to this would be for OffsetArrays to forward the iteration to the parent, however this was decided against in the PR above. In any case this is not a general solution, and addressing the issue in Base would be ideal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions