Skip to content

Commit 817e81c

Browse files
Lilith HafnerLilith Hafner
authored andcommitted
avoid overhead of views where reasonable
1 parent 62e1fb7 commit 817e81c

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

base/sort.jl

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -857,8 +857,20 @@ function sort!(v::AbstractVector{T}, lo::Integer, hi::Integer, a::AdaptiveSort,
857857
u[i] -= u_min
858858
end
859859

860-
u2 = radix_sort!(view(u, lo:hi), 1, hi-lo+1, bits, reinterpret(U, workspace(v, t, hi-lo+1)))
861-
uint_unmap!(v, u2, lo, hi, o, u_min)
860+
# If it is reasonable to allocate a workspace with indices 1:hi...
861+
if lo >= 1 && fld(hi, hi-lo+1) < 100
862+
# ...do it to avoid the overhead of a view
863+
t2 = reinterpret(U, workspace(v, t, hi))
864+
u2 = radix_sort!(u, lo, hi, bits, t2)
865+
uint_unmap!(v, u2, lo, hi, o, u_min)
866+
else # ...if that is impossible or unreasonable,
867+
# use a view to bring the input into the indices
868+
# 1:hi-lo+1 and allocate only what is necessary
869+
t2 = reinterpret(U, workspace(v, t, hi-lo+1))
870+
u2 = radix_sort!(view(u, lo:hi), 1, hi-lo+1, bits, t2)
871+
uint_unmap!(view(v, lo:hi), u2, 1, hi-lo+1, o, u_min)
872+
end
873+
v
862874
end
863875

864876
## generic sorting methods ##
@@ -1394,8 +1406,8 @@ end
13941406

13951407
function uint_unmap!(v::AbstractVector, u::AbstractVector{U}, lo::Integer, hi::Integer,
13961408
order::Ordering, offset::U=zero(U)) where U <: Unsigned
1397-
@inbounds for (i, j) in zip(lo:hi, eachindex(u))
1398-
v[i] = uint_unmap(eltype(v), u[j]+offset, order)
1409+
@inbounds for i in lo:hi
1410+
v[i] = uint_unmap(eltype(v), u[i]+offset, order)
13991411
end
14001412
v
14011413
end

0 commit comments

Comments
 (0)