Type-instability indexing tuple

display is itself not stable and you can’t really fix that (nor is it a function that you might care about trying to), but for small tuples, you can get rid of the type instability introduced by the loop by using map instead. E.g. compare the output of:

function f(x)
   for k in eachindex(x)
      identity(x[k])
   end
end
@code_warntype f(a)

which will show the getindex is not inferred (since the value of k is unknown at compile time and the return type will depend on it):

│   %9  = Base.getindex(x, k)::Union{StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}}, UnitRange{Int64}}

vs. the output of:

function f(x)
   map(identity, x)
end
@code_warntype f(a)

which is fully inferred. Note though even this will not be inferred if the tuple has more than 16 elements.

1 Like