Does union cause type instability?

a=Vector{Union{Missing, Int64}}()
push!(a,1)
push!(a,missing)

push! to the union vector.Can this cause type instability?

Type stabilty is generally a property of functions, not collections.

Thanks.If I wrote a function.like the following.

function f(x)#x is a vector
    a=Vector{Union{Missing, Int64}}()
    for i in x 
        b=m(i)#for example ,function m  can generate Type Int64 or missing.
        push!(a,b)
    end
    return a
end

Does the function cause type instabilty?

In this code everything depends on the function m. Function f itself causes no problems.

But if the function m return Int64 or missing,will m cause type instabilty?

No. Julia implements Union by storing a separate variable which tells which type the value has. The code then has branches, but no general type instability. You can check code stability yourself by using macro @code_warntype like @code_warntype f([1,2,3]).

1 Like