Lesson 8 of 9 · 26m
LuaJIT Performance, FFI, and Memory Behavior
Write hot-path Lua that cooperates with LuaJIT: reduce allocation churn, understand FFI cdata, localize lookups, and measure before optimizing.
Lua performance advice is full of folklore because LuaJIT is both very fast and very specific about what it can optimize. I have seen teams shave nanoseconds off table indexing while allocating thousands of short-lived tables per request. The interpreter notices the allocations; the garbage collector notices them even more. Good Lua performance starts with understanding object lifetimes and control flow, not with cargo-culted syntax tricks.
Measure the real path first
Measure the whole request path before micro-optimizing: nginx timing variables, application tracing, upstream latency, and production-like traffic. For CPU-heavy Lua, LuaJIT's dump tooling shows whether code is traced, interpreted, or repeatedly aborted:
luajit -jdump hotpath.luaA function that looks hot in source may be irrelevant because the network dominates; a tiny body-filter transformation may run for every response chunk.
Allocation is often the real cost
Lua strings are immutable and tables are heap objects. Prefer accumulating parts and joining once over repeatedly concatenating large strings:
local parts = {}
for i = 1, 10000 do parts[#parts + 1] = "item-" .. i end
local body = table.concat(parts, ",")Cache immutable lookup tables at module scope and localize frequently used functions:
local lower = string.lower
local methods = { GET = true, POST = true, PUT = true, DELETE = true }
local function valid_method(method) return methods[method] == true endLocalization is a small optimization, not magic. Allocation reduction usually matters more in request-heavy systems.
FFI is powerful because it is not Lua data
LuaJIT's foreign function interface manipulates C-compatible memory directly:
local ffi = require("ffi")
ffi.cdef[[ typedef struct { double x; double y; } vec2; ]]
local point = ffi.new("vec2", 3.0, 4.0)
point.x = point.x + 1.5point is cdata, not a normal Lua table. It has distinct equality, copying, lifetime, and metamethod behavior. Passing cdata across abstraction boundaries without documenting that fact creates subtle bugs.
FFI does not remove memory ownership questions
If C memory comes from a library, who frees it? If Lua allocates memory and passes it to C, can C retain the pointer? If a finalizer or ffi.gc is attached, when does it run? These are ownership questions, not syntax questions. A crash after request completion usually means one side retained memory owned by the other.
Trace-friendly code is boring code
LuaJIT does best with stable types, predictable branches, monomorphic shapes, and simple inner loops. Constantly changing table layouts, varargs abuse, exceptions in hot paths, and alternating data types make tracing harder. Write the straightforward version first, measure it, then simplify the hot loop. Do not distort the entire codebase for a profiler artifact.
Memory behavior is operational behavior
In OpenResty, memory growth may come from request-local leaks, module-level caches, shared dictionary pressure, FFI allocations, or fragmented pools. A single worker can look healthy while another balloons because traffic distribution differs. Observe per-worker memory, cache hit rates, GC pauses where available, and queue depth. Performance tuning without operational visibility becomes superstition.
Field notes
localfunction lookup helps, but allocation reduction usually matters more in request-heavy systems.- Do not concatenate large strings incrementally in loops; accumulate parts and use
table.concat. - FFI cdata is not a Lua table; document ownership and conversion points explicitly.
- Disable or bound caches before optimizing lookup logic; unbounded caches are slow-motion outages.
Was this lesson helpful?