Open mattsignorelli opened 5 months ago
Minimal example:
julia> foo(v; y::Union{Nothing,<:Integer}=nothing) = isnothing(y) ? v[1] : v[y]
foo (generic function with 1 method)
julia> @btime foo($[1,2,3];y=1);
286.996 ns (3 allocations: 96 bytes)
julia> foo(v; y::Union{Nothing,Integer}=nothing) = isnothing(y) ? v[1] : v[y]
foo (generic function with 1 method)
julia> @btime foo($[1,2,3];y=1);
2.609 ns (0 allocations: 0 bytes)
julia> foo(v; y::Union{Nothing,T}=nothing) where {T<:Integer} = isnothing(y) ? v[1] : v[y]
foo (generic function with 1 method)
julia> @btime foo($[1,2,3];y=1);
3.002 ns (0 allocations: 0 bytes)
I originally posted this here in the discourse.
Consider this function which simply returns the argument at the specified index
idx
ory
in the vectorv
:With Benchmark tools we see:
No surprises here, zero allocations. Now let’s make one tiny change and let the keyword argument type be
Union{Nothing, <:Integer}
instead ofUnion{Nothing, Integer}
, so:Now we see with
foo2
Julia was installed through Juliaup. My
versioninfo()
: