Closure caching question

Where, in the Luau source code, can I find the heuristics for closure caching?

The heuristics of closure caching in Luau are explained on the Luau website as follows:

To make closure creation cheaper, Luau compiler implements closure caching - when multiple executions of the same function expression are guaranteed to result in the function object that is semantically identical, the compiler may cache the closure and always return the same object. This changes the function identity which may affect code that uses function objects as table keys, but preserves the calling semantics - compiler will only do this if calling the original (cached) function behaves the same way as a newly created function would. The heuristics used for this optimization are subject to change; currently, the compiler will cache closures that have no upvalues, or all upvalues are immutable (see previous section) and are declared at the module scope, as the module scope is (almost always) evaluated only once.

If you’re looking for the area in the source code, the closure caching decision is made in the compiler’s bytecode emitter when compiling a function expression. If you want an exact location, look in luau/Compiler/src/Compiler.cpp, there is a function bool shouldShareClosure(AstExprFunction* func) which decides whether a function literal is “shareable” (i.e., eligible for closure caching/sharing). Hope this helps!

2 Likes

Thanks a bunch!

character limit

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.