From 5c2cd662964ebbf510e5eb47bbe2a2d2ee3c42fc Mon Sep 17 00:00:00 2001 From: N5N3 <2642243996@qq.com> Date: Mon, 28 Feb 2022 22:52:33 +0800 Subject: [PATCH] Avoid dynamic allocation in `hypot` (#44357) --- base/math.jl | 5 +++-- test/math.jl | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/base/math.jl b/base/math.jl index af86c11c01b261..104b8ca41c0146 100644 --- a/base/math.jl +++ b/base/math.jl @@ -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) @@ -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) diff --git a/test/math.jl b/test/math.jl index af280066f2f22e..625ab4285751f7 100644 --- a/test/math.jl +++ b/test/math.jl @@ -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