Skip to content

Commit

Permalink
broadcast: simplify ndims (#50695)
Browse files Browse the repository at this point in the history
The extra dispatch was inconsistently used, which seemed unnecessary.
Also make sure T is captured as a Type parameter in the closure (fast),
instead of a value (potentially slow).

Very small difference measured (probably just noise):
broadcast  (1) |   115.68 |   0.78 |  0.7 |    4245.13 |   849.62 before
broadcast  (1) |   109.73 |   0.80 |  0.7 |    4243.89 |   788.25 after
  • Loading branch information
vtjnash authored Jul 31, 2023
1 parent a712455 commit 6f0a9e5
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 10 deletions.
10 changes: 3 additions & 7 deletions base/broadcast.jl
Original file line number Diff line number Diff line change
Expand Up @@ -277,16 +277,12 @@ Base.IteratorSize(::Type{T}) where {T<:Broadcasted} = Base.HasShape{ndims(T)}()
Base.ndims(BC::Type{<:Broadcasted{<:Any,Nothing}}) = _maxndims(fieldtype(BC, :args))
Base.ndims(::Type{<:Broadcasted{<:AbstractArrayStyle{N},Nothing}}) where {N<:Integer} = N

_maxndims(T::Type{<:Tuple}) = reduce(max, (ntuple(n -> _ndims(fieldtype(T, n)), Base._counttuple(T))))
_maxndims(::Type{<:Tuple{T}}) where {T} = ndims(T)
_maxndims(::Type{<:Tuple{T}}) where {T<:Tuple} = _ndims(T)
_maxndims(::Type{T}) where {T<:Tuple} = reduce(max, ntuple(n -> (F = fieldtype(T, n); F <: Tuple ? 1 : ndims(F)), Base._counttuple(T)))
_maxndims(::Type{<:Tuple{T}}) where {T} = T <: Tuple ? 1 : ndims(T)
function _maxndims(::Type{<:Tuple{T, S}}) where {T, S}
return T<:Tuple || S<:Tuple ? max(_ndims(T), _ndims(S)) : max(ndims(T), ndims(S))
return max(T <: Tuple ? 1 : ndims(T), S <: Tuple ? 1 : ndims(S))
end

_ndims(x) = ndims(x)
_ndims(::Type{<:Tuple}) = 1

Base.IteratorEltype(::Type{<:Broadcasted}) = Base.EltypeUnknown()

## Instantiation fills in the "missing" fields in Broadcasted.
Expand Down
3 changes: 0 additions & 3 deletions test/subarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,6 @@ end
# with the exception of Int-slicing
oindex = (:, 6, 3:7, reshape([12]), [8,4,6,12,5,7], [3:7 1:5 2:6 4:8 5:9], reshape(2:11, 2, 5))

_ndims(::AbstractArray{T,N}) where {T,N} = N
_ndims(x) = 1

if testfull
let B = copy(reshape(1:13^3, 13, 13, 13))
@testset "full tests: ($o1,$o2,$o3)" for o3 in oindex, o2 in oindex, o1 in oindex
Expand Down

0 comments on commit 6f0a9e5

Please sign in to comment.