Skip to content

Commit 5c2cd66

Browse files
N5N3staticfloat
authored andcommitted
Avoid dynamic allocation in hypot (JuliaLang#44357)
1 parent 5964c04 commit 5c2cd66

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

base/math.jl

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -671,7 +671,8 @@ true
671671
```
672672
"""
673673
hypot(x::Number) = abs(float(x))
674-
hypot(x::Number, y::Number, xs::Number...) = _hypot(float.(promote(x, y, xs...))...)
674+
hypot(x::Number, y::Number) = _hypot(promote(float(x), y)...)
675+
hypot(x::Number, y::Number, xs::Number...) = _hypot(promote(float(x), y, xs...))
675676
function _hypot(x, y)
676677
# preserves unit
677678
axu = abs(x)
@@ -743,7 +744,7 @@ end
743744
end
744745
_hypot(x::ComplexF16, y::ComplexF16) = Float16(_hypot(ComplexF32(x), ComplexF32(y)))
745746

746-
function _hypot(x...)
747+
function _hypot(x::NTuple{N,<:Number}) where {N}
747748
maxabs = maximum(abs, x)
748749
if isnan(maxabs) && any(isinf, x)
749750
return typeof(maxabs)(Inf)

test/math.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1399,3 +1399,12 @@ end
13991399
# the compiler ever gets good enough to figure
14001400
# that out by itself, move this to inference).
14011401
@test code_typed(x->Val{x^0.0}(), Tuple{Float64})[1][2] == Val{1.0}
1402+
1403+
function f44336()
1404+
as = ntuple(_ -> rand(), Val(32))
1405+
@inline hypot(as...)
1406+
end
1407+
@testset "Issue #44336" begin
1408+
f44336()
1409+
@test (@allocated f44336()) == 0
1410+
end

0 commit comments

Comments
 (0)