# Recursive closures/inner functions -- how to avoid boxing?

**URL:** <https://discourse.julialang.org/t/recursive-closures-inner-functions-how-to-avoid-boxing/124758>\
**Category:** General Usage\
**Tags:** question, closure\
**Created:** [January 14, 2025, 10:34am UTC](https://discourse.julialang.org/t/recursive-closures-inner-functions-how-to-avoid-boxing/124758 "2025-01-14T10:34:21Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![Mason](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mason/32/2423_2.png) [@Mason](https://discourse.julialang.org/u/Mason)\
**Post date:** [January 14, 2025, 11:45am UTC](https://discourse.julialang.org/t/recursive-closures-inner-functions-how-to-avoid-boxing/124758/3 "2025-01-14T11:45:28Z")

</div>

@uniment was on quite the crusade against this issue a while ago, and there’s some issues and discussions all over the place here on Discourse and Github about it from that era.

Here’s some breadcrumbs if you want to explore (a subset of) the discussion that happened back then:

- [Performant Recursive Anonymous Functions](https://discourse.julialang.org/t/performant-recursive-anonymous-functions/90984)
- [Locally-Scoped Named Functions have Surprising Behavior that Causes Poor Performance · Issue #47760 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/47760)
- [implement local const · Issue #5148 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/5148)
- [Do not capture recursive local function's self-identifier (to avoid box) · Issue #53295 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/53295)

One hacky trick you can use here is `var"#self#"` to refer to the function itself, i.e.

```julia-repl
julia> function outer()
           function inner()
               false && var"#self#"()
           end
           inner
       end
outer (generic function with 1 method)

julia> typeof(outer()).types
svec()

julia> @btime outer()()
  1.082 ns (0 allocations: 0 bytes)
false

```

This is not a particularly good idea though, and I would not recommend doing it in general. The PR I mention in ["A Tragedy of Julia’s Type System" - #36 by Mason](https://discourse.julialang.org/t/a-tragedy-of-julia-s-type-system/124619/36) should be able to fix this issue as well.

---

_[View the full topic](https://discourse.julialang.org/t/recursive-closures-inner-functions-how-to-avoid-boxing/124758)._
