# Type-Instability when calling \`fieldtypes\`

**URL:** https://discourse.julialang.org/t/type-instability-when-calling-fieldtypes/91881
**Category:** Performance
**Tags:** question, potential-bug
**Created:** [December 20, 2022, 1:05am UTC](https://discourse.julialang.org/t/type-instability-when-calling-fieldtypes/91881 "2022-12-20T01:05:21Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![uniment](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/uniment/32/24532_2.png) [@uniment](https://discourse.julialang.org/u/uniment)
#### Post date: [December 20, 2022, 1:05am UTC](https://discourse.julialang.org/t/type-instability-when-calling-fieldtypes/91881/1 "2022-12-20T01:05:21Z")

</div>

Is there a way to make `fieldtypes` not be type-unstable here?

```julia
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
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)

```
