You may find the discussion above helpful. Especially, the comment made by @baggepinnen
Re @codewarntype
, it’s just a helpful quick-way to check for all type-instabilities like so
julia> function f(x, y)
return x + y
end
f (generic function with 1 method)
julia> @code_warntype f(1, 2)
Variables
#self#::Core.Compiler.Const(f, false)
x::Int64
y::Int64
Body::Int64
1 ─ %1 = (x + y)::Int64
└── return %1
julia> @code_warntype f(1.0, 2.0)
Variables
#self#::Core.Compiler.Const(f, false)
x::Float64
y::Float64
Body::Float64
1 ─ %1 = (x + y)::Float64
└── return %1
julia> x = 1
1
julia> y = 2
2
julia> function g()
return x + y
end
g (generic function with 1 method)
julia> @code_warntype g()
Variables
#self#::Core.Compiler.Const(g, false)
Body::Any
1 ─ %1 = (Main.x + Main.y)::Any
└── return %1
In the above example, f(x, y)
is type-stable (all types are known at compile-time) but g()
is not as the return type is not known at compile time. The Any
in the @code_warntype
output for g()
will likely show up in your REPL in red. The reason is that in f(x,y)
I pass x, y as arguments but they are global variables for the function g()
.
Notice that for all functions a specialized compiled code is generated depending on your argument type. @code_warntype
simply allows you to see that. Please keep in mind that all type-instabilities are not important as mentioned in the link below. There are some functions in Base
like Base.getindex
which are type-unstable by design. Similarly, the iterator interface for a for loop will also be type-unstable and so on. So don’t worry about all type-instabilities!
https://docs.julialang.org/en/v1/manual/performance-tips/#man-code-warntype-1