LU

Lua Performance

Lua performance optimization: locals, table reuse, LuaJIT FFI, and allocation reduction

Details

Language / Topic
luaLua
Category
Performance

Rules

balanced
- Localize frequently accessed globals at the top of hot functions: `local floor = math.floor` — local variable access is faster than global table lookup.
- Avoid creating new tables inside tight loops — pre-allocate with `{}` outside the loop and clear/reuse them with `table.clear` (LuaJIT) or manual key deletion.
- Use LuaJIT FFI (`ffi.new`, `ffi.cdef`) for C struct manipulation instead of Lua table approximations — it avoids boxing overhead.
- Use `table.move(src, f, e, t, dst)` (Lua 5.3+) instead of a `for` loop for bulk array copying — it is implemented in C.
- Avoid `string.gmatch` and `string.gsub` in hot paths with large strings — prefer `string.find` with `init` position for incremental parsing.
- Use `jit.on()` / `jit.off()` in LuaJIT to selectively enable the JIT compiler for specific functions — trace complex functions with `jit.dump`.
- Reduce upvalue count in closures — each upvalue adds overhead to closure creation and GC tracing.