For statement type instability

It’s true that tuples of heterogeneous types are totally fine, as long as the tuple type is known to the compiler; it’s no different than a struct with heterogeneous members. But you have to be very careful about iteration over a heterogeneous tuple.

for loops over heterogeneous tuples, in particular, are not unrolled (even though the compiler knows the length) and can lead to type-instability issues for heterogeneous tuples. Various threads have complained about this, e.g. Unrolling loops over tuples - why so hard? - #15 by matthias314 and Manually unroll operations with objects of tuple - #2 by mauro3, and there is an old package Unrolled.jl that tries to do this for you.

However, what’s less known is that certain functions like the map, mapreduce, and (as of Julia 1.8 thanks to julia#31901) foreach functions can be completely unrolled for tuple arguments, so e.g.

foreach((One(), Two(),3,"4")) do number
    
end

is completely unrolled IIRC, and it can potentially be type stable depending on what you do inside the loop. (One difficulty with foreach is that, because the “loop body” is a closure, you can easily get bitten by julia#15276 if you want to assign to a local variable inside the loop.)

4 Likes