Search code examples
lualuajit

Is accessing a Lua table field faster then accessing a cdata field?


Say I have a cdata variable (a result of a FFI query). Then I copy its fields to a Lua table. What is faster: access fields of the Lua table or of the original cdata variable?


Solution

  • With disabled JIT, table key lookup is the way much faster due to LuaJIT table internal structure and collision handling optimizations (e.g. Brent's variation). For cdata TGETS/TGETV implies a metamethod lookup and its further execution. Here is the method implementing field (i.e. key) lookup.

    With enabled JIT both table slot and structure field addresses/offsets are specialized on the trace with several assertion guards prior it. Omitting such assertion failures (e.g. caused by table reallocation, that leads to the slot address invalidation), the performance difference can be considered neglible.

    I see nice benchmarks by @mons-anderson also confirming it.