# For statement type instability

**URL:** <https://discourse.julialang.org/t/for-statement-type-instability/118817>\
**Category:** General Usage\
**Tags:** question, bug, performance\
**Created:** [August 30, 2024, 3:49pm UTC](https://discourse.julialang.org/t/for-statement-type-instability/118817 "2024-08-30T15:49:55Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [August 31, 2024, 12:45pm UTC](https://discourse.julialang.org/t/for-statement-type-instability/118817/7 "2024-08-31T12:45:28Z")

</div>

> [@0samuraiE](#):
>
> I knew about that article, but did not know that the rule applied to Tuple.

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](https://discourse.julialang.org/t/unrolling-loops-over-tuples-why-so-hard/103428/15) and [Manually unroll operations with objects of tuple - #2 by mauro3](https://discourse.julialang.org/t/manually-unroll-operations-with-objects-of-tuple/11604/2), and there is an old package [Unrolled.jl](https://github.com/cstjean/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](https://github.com/JuliaLang/julia/pull/31901)) `foreach` functions _can be_ completely unrolled for tuple arguments, so e.g.

```julia
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](https://github.com/JuliaLang/julia/issues/15276) if you want to assign to a local variable inside the loop.)

---

_[View the full topic](https://discourse.julialang.org/t/for-statement-type-instability/118817)._
