@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
- Locally-Scoped Named Functions have Surprising Behavior that Causes Poor Performance · Issue #47760 · JuliaLang/julia · GitHub
- implement local const · Issue #5148 · JuliaLang/julia · GitHub
- Do not capture recursive local function's self-identifier (to avoid box) · Issue #53295 · JuliaLang/julia · GitHub
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.