Type inference when just making a tuple


I’m seeing some type instabilities in my code.

I saw that converting a vector into a tuple generates instabilities. Here a very simple example

using Test

function prova(vec)
    return Tuple(vec)

T = Float64
a = rand(T, 3)

@inferred prova(a)
ERROR: return type Tuple{Float64, Float64, Float64} does not match inferred return type Tuple{Vararg{Float64}}
 [1] error(s::String)
   @ Base ./error.jl:35
 [2] top-level scope
   @ Untitled-1:35

It is surprising how such a simple code can generate instabilities.

It doesn’t know the length of vec, so it’s not too surprising - that’s where the Vararg comes from.

1 Like

Ok, makes sense. But how to solve this?

Use StaticArrays.jl depending on the problem size

1 Like

Note that if your static arrays vary in size you’ll run into the exact same issue. Perhaps the better question is why you want to convert vectors into tuples?


The reason was to have better performances. But maybe vectors are more suitable for my case.

The main reason Tuples have better performance than Vectors is that the compiler knows their length, so they can be stored on the stack (not heap allocated). If your data has variable length, then Julia needs to compile a new function for every unique length. In this case, a vector is almost always the right choice.