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

@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:

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

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 should be able to fix this issue as well.

2 Likes