Type instability - two examples: yes/no?

question

#1

Which of these functions is type-unstable? If unstable:

  1. What are the performance implications?
  2. What’s the output in @code_warntype that would indicate instability?

(For the record: I know how to parameterize them; I’m trying to determine when parameterization makes sense.)

Thanks!

function foo1(v::Vector)
  T = eltype(v)
  return one(T)
end
function foo2(v::Vector, x::Integer)
  T = eltype(v)
  oneT = one(T)  # explicit assignment here just to make sure we allocate mem.
  return (oneT < x)
end

#2

They’re not unstable from what I can see. Parameterization doesn’t change functions. In fact, if you check the compiled code, T is definitely computed at compile time, so it’s no different than using a type parameter even in the compiled code.


#3

None. Assuming none of the functions you called are overwritten in a unstable way.

For these, none. For type instability, it depends.

Red.


#4

Thanks. I’m surprised that the first one isn’t type-unstable, since the type of the output depends on the result of a calculation within the function. Perhaps I have a faulty definition of type stability.


#5

If one(T) is type-stable (it probably is for any type you’re using), then by knowing T (which is known because of dispatch, methods auto-specialize in Julia), you know the output type of one(T). Thus you know the output type, and every intermediate type. It’s all strictly typed.