Is there a way to make fieldtypes
not be type-unstable here?
julia> struct Foo{A,B} a::A; b::B end
julia> ft1(o::T) where T = Tuple(T.types)
ft1 (generic function with 1 method)
julia> ft2(o::T) where T = fieldtypes(T)
ft2 (generic function with 1 method)
julia> @code_warntype ft1(Foo(1,2))
MethodInstance for ft1(::Foo{Int64, Int64})
from ft1(o::T) where T in Main at REPL[5]:1
Static Parameters
T = Foo{Int64, Int64}
Arguments
#self#::Core.Const(ft1)
o::Foo{Int64, Int64}
Body::Core.SimpleVector
1 ─ %1 = Base.getproperty($(Expr(:static_parameter, 1)), :types)::Core.Const(svec(Int64, Int64))
└── return %1
julia> @code_warntype ft2(Foo(1,2))
MethodInstance for ft2(::Foo{Int64, Int64})
from ft2(o::T) where T in Main at REPL[6]:1
Static Parameters
T = Foo{Int64, Int64}
Arguments
#self#::Core.Const(ft2)
o::Foo{Int64, Int64}
Body::Tuple
1 ─ %1 = Main.fieldtypes($(Expr(:static_parameter, 1)))::Tuple
└── return %1
The type instability causes performance degradation:
julia> using BenchmarkTools
julia> @btime ft1(Foo(1,2))
2.300 ns (0 allocations: 0 bytes)
(Int64, Int64)
julia> @btime ft2(Foo(1,2))
94.819 ns (2 allocations: 96 bytes)
(Int64, Int64)