Skip to content

Commit

Permalink
Avoid dynamic allocation in hypot (JuliaLang#44357)
Browse files Browse the repository at this point in the history
  • Loading branch information
N5N3 authored and staticfloat committed Mar 2, 2022
1 parent 5964c04 commit 5c2cd66
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
5 changes: 3 additions & 2 deletions base/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,8 @@ true
```
"""
hypot(x::Number) = abs(float(x))
hypot(x::Number, y::Number, xs::Number...) = _hypot(float.(promote(x, y, xs...))...)
hypot(x::Number, y::Number) = _hypot(promote(float(x), y)...)
hypot(x::Number, y::Number, xs::Number...) = _hypot(promote(float(x), y, xs...))
function _hypot(x, y)
# preserves unit
axu = abs(x)
Expand Down Expand Up @@ -743,7 +744,7 @@ end
end
_hypot(x::ComplexF16, y::ComplexF16) = Float16(_hypot(ComplexF32(x), ComplexF32(y)))

function _hypot(x...)
function _hypot(x::NTuple{N,<:Number}) where {N}
maxabs = maximum(abs, x)
if isnan(maxabs) && any(isinf, x)
return typeof(maxabs)(Inf)
Expand Down
9 changes: 9 additions & 0 deletions test/math.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1399,3 +1399,12 @@ end
# the compiler ever gets good enough to figure
# that out by itself, move this to inference).
@test code_typed(x->Val{x^0.0}(), Tuple{Float64})[1][2] == Val{1.0}

function f44336()
as = ntuple(_ -> rand(), Val(32))
@inline hypot(as...)
end
@testset "Issue #44336" begin
f44336()
@test (@allocated f44336()) == 0
end

0 comments on commit 5c2cd66

Please sign in to comment.