Skip to content

Commit f49cee2

Browse files
author
Andy Ferris
committed
Make view of range with range be a range
Typical `AbstractRange` types are compact and immutable, and we can remove the overhead of `SubArray` in this case while the cost of `view` remains O(1). Here we specialize only on valid combinations of integer ranges, otherwise still relying on `SubArray`.
1 parent d44944d commit f49cee2

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

base/subarray.jl

+18
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,24 @@ function view(A::AbstractArray, I::Vararg{Any,N}) where {N}
134134
unsafe_view(_maybe_reshape_parent(A, index_ndims(J...)), J...)
135135
end
136136

137+
# Ranges tend to be compact & immutable
138+
function view(r1::OneTo, r2::OneTo)
139+
@_propagate_inbounds_meta
140+
getindex(r1, r2)
141+
end
142+
function view(r1::AbstractUnitRange, r2::AbstractUnitRange{<:Integer})
143+
@_propagate_inbounds_meta
144+
getindex(r1, r2)
145+
end
146+
function view(r1::AbstractUnitRange, r2::StepRange{<:Integer})
147+
@_propagate_inbounds_meta
148+
getindex(r1, r2)
149+
end
150+
function view(r1::StepRange, r2::AbstractRange{<:Integer})
151+
@_propagate_inbounds_meta
152+
getindex(r1, r2)
153+
end
154+
137155
function unsafe_view(A::AbstractArray, I::Vararg{ViewIndex,N}) where {N}
138156
@_inline_meta
139157
SubArray(A, I)

test/ranges.jl

+7
Original file line numberDiff line numberDiff line change
@@ -1263,3 +1263,10 @@ end
12631263
@test step(x) == 0.0
12641264
@test x isa StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}
12651265
end
1266+
1267+
@testset "Views of ranges" begin
1268+
@test view(Base.OneTo(10), Base.OneTo(5)) === Base.OneTo(5)
1269+
@test view(1:10, 1:5) === 1:5
1270+
@test view(1:10, 1:2:5) === 1:2:5
1271+
@test view(1:2:9, 1:5) === 1:2:9
1272+
end

0 commit comments

Comments
 (0)