Code stability with for loop

With for loops, @code_warntype can have one yellow/warning about union. Is it ok performance-wise or am I doing something wrong here? example

function f(a)
    c = zero(eltype(a))
    ns = 10
    for i in 1:10
        c += sin(a[i])
    end
    c
end

a=rand(10)
@code_warntype f(a)
Variables
  #self#::Core.Compiler.Const(f, false)
  a::Array{Float64,1}
  c::Float64
  ns::Int64
  @_5::Union{Nothing, Tuple{Int64,Int64}}
  i::Int64

Body::Float64
1 ─ %1  = Main.eltype(a)::Core.Compiler.Const(Float64, false)
β”‚         (c = Main.zero(%1))
β”‚         (ns = 10)
β”‚   %4  = (1:10)::Core.Compiler.Const(1:10, false)
β”‚         (@_5 = Base.iterate(%4))
β”‚   %6  = (@_5::Core.Compiler.Const((1, 1), false) === nothing)::Core.Compiler.Const(false, false)
β”‚   %7  = Base.not_int(%6)::Core.Compiler.Const(true, false)
└──       goto #4 if not %7
2 β”„ %9  = @_5::Tuple{Int64,Int64}::Tuple{Int64,Int64}
β”‚         (i = Core.getfield(%9, 1))
β”‚   %11 = Core.getfield(%9, 2)::Int64
β”‚   %12 = c::Float64
β”‚   %13 = Base.getindex(a, i)::Float64
β”‚   %14 = Main.sin(%13)::Float64
β”‚         (c = %12 + %14)
β”‚         (@_5 = Base.iterate(%4, %11))
β”‚   %17 = (@_5 === nothing)::Bool
β”‚   %18 = Base.not_int(%17)::Bool
└──       goto #4 if not %18
3 ─       goto #2
4 β”„       return c

here, @_5::Union{Nothing, Tuple{Int64,Int64}} is yellow/warning. Thanks!

That’s nothing to worry about. The link below may be helpful

https://docs.julialang.org/en/v1/manual/performance-tips/index.html#man-code-warntype-1

Basically, the yellow colored warnings are typically low-priority β€œtype instabilities”. The reply here addresses your question too How to prevent type instability in for loops?. To quote from the first reply, β€œ(such type instabilities) is a consequence of the iterator interface which returns nothing when the end of the iterator is reached. Note that the line you cited from the @code_warntype output is colored in yellow (not red, which indicates β€œtrue” type instabilities)”

4 Likes