# How to make the compiler unroll a finite recursion?

**URL:** <https://discourse.julialang.org/t/how-to-make-the-compiler-unroll-a-finite-recursion/142994>\
**Category:** Performance\
**Created:** [November 17, 2026, 6:52pm UTC](https://discourse.julialang.org/t/how-to-make-the-compiler-unroll-a-finite-recursion/142994 "2026-11-17T18:52:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![matthias314](https://avatars.discourse-cdn.com/v4/letter/m/a88e4f/32.png) [@matthias314](https://discourse.julialang.org/u/matthias314)\
**Post date:** [November 17, 2026, 6:52pm UTC](https://discourse.julialang.org/t/how-to-make-the-compiler-unroll-a-finite-recursion/142994/1 "2026-11-17T18:52:41Z")

</div>

How can I convince the compiler that a recursion is finite and can be unrolled? It works for me when the recursion has one step (some function calling itself), but not for two steps (two functions calling each other).

Here is an example: I move elements from a tuple `t2` to a tuple `t1`:

```julia-auto
f(t1, ::Tuple{}) = t1
f(t1, t2) = f((t1..., t2[1]), t2[2:end])
ff(t) = f((), t)

g1(t1, ::Tuple{}) = t1
g1(t1, t2) = g2((t1..., t2[1]), t2[2:end])
g2(t1, t2) = g1(t1, t2)
gg(t) = g1((), t)

```

The compiler knows that the recursion in `f` ends, but it doesn’t know it for the one involving `g1` and `g2`:

```julia-auto
julia> t = (1, 2, 3); ff(t), gg(t)
((1, 2, 3), (1, 2, 3))

julia> using Chairmarks; @b ff($t), gg($t)
(2.456 ns, 26.151 ns (3 allocs: 80 bytes))

```

Is there a way to encourage the compiler to unroll the recursion for `g1` and `g2`? I’ve tried to decorate the code with many `@inline` and `@assume_effects :total`, but that didn’t help.

---

<div class="post-metadata">

**Author:** ![matthias314](https://avatars.discourse-cdn.com/v4/letter/m/a88e4f/32.png) [@matthias314](https://discourse.julialang.org/u/matthias314)\
**Post date:** [November 17, 2026, 6:56pm UTC](https://discourse.julialang.org/t/how-to-make-the-compiler-unroll-a-finite-recursion/142994/2 "2026-11-17T18:56:54Z")

</div>

When I also define

```julia-auto
g2(t1, ::Tuple{}) = t1

```

(which will never be called), then it does work!

```julia-auto
julia> using Chairmarks; @b ff($t), gg($t)
(2.375 ns, 2.377 ns)

```

Are there other ways? In the application I have in mind, I don’t want to create additional methods for `g2`.
