BenchmarkTools.jl icon indicating copy to clipboard operation
BenchmarkTools.jl copied to clipboard

Spurious performance penalty for single-element Union

Open timholy opened this issue 4 years ago • 0 comments

add2f(x) = f(x[1]) + f(x[2])
# `f` has multiple methods
f(z::Integer) = 2*z
f(z::AbstractFloat) = 111*z
f(z::AbstractString) = 0
f(z::AbstractArray) = length(z)

Here's the strange part:

julia> using BenchmarkTools

julia> @btime add2f(z) setup=(x = rand(); y = rand(); z = [x, y])
  1.729 ns (0 allocations: 0 bytes)
26.55487721682921

julia> @btime add2f(z) setup=(x = rand(); y = rand(); z = Union{Float64}[x, y])
  21.631 ns (3 allocations: 48 bytes)
171.91145933156855

julia> typeof(Union{Float64}[1.0, 2.0])
Vector{Float64} (alias for Array{Float64, 1})

Consequently I am pretty sure this is an issue here rather than in Julia itself.

timholy avatar Oct 27 '21 07:10 timholy