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