Skip to content

optimize: skip redundant work for empty objects and arrays - #130

Open
sys9kdr wants to merge 1 commit into
openresty:masterfrom
sys9kdr:optimize/empty-containers
Open

sys9kdr wants to merge 1 commit into
openresty:masterfrom
sys9kdr:optimize/empty-containers

Conversation

@sys9kdr

@sys9kdr sys9kdr commented Oct 25, 2026

Copy link
Copy Markdown

Summary

Empty objects and arrays are common in JSON-RPC/LSP traffic and in configuration
data, but lua-cjson does redundant work for them in both directions:

  • the decoder runs the full token dispatcher on the closing } / ]
  • the encoder scans an empty table twice with lua_next() when encoding it as
    an object (once in lua_array_length(), once in json_append_object())

Changes

  • decode: after { / [, consume } / ] directly when it is the next
    byte. Whitespace, comments, decode_max_depth accounting and error messages
    are unchanged; anything other than the immediate closing bracket still uses
    the existing token path.
  • encode: when lua_array_length() returns 0 the table has no entries (any
    entry makes it return -1), so write {} directly. This runs after the
    existing empty_array_mt check, so cjson.empty_array still encodes as [].

No API or configuration changes; encoded output is unchanged.

Benchmarks

Payload: 20,000 empty tables ([{},...], 60 KB JSON). LuaJIT 2.1, AMD Ryzen
AI MAX+ 395 (WSL2), pinned to one core. Fixed iteration counts; gcc 15 rounds,
clang 9 rounds; base and patched processes interleaved; medians reported.

compiler case base (µs/op) patched (µs/op) ratio
gcc encode 704 566 0.80
gcc decode 650 633 0.97
clang encode 681 587 0.86
clang decode 689 646 0.94

perf stat -e instructions:u (slope of two iteration counts):
encode 14.42M → 11.32M (-21.5%), decode 13.39M → 12.55M (-6.3%).

An identical-binary control run is within 0.5%, and pretty-decode (a payload
with no empty containers) is unchanged (0.99–1.01), as expected.

Test plan

  • tests/test.lua passes on LuaJIT 2.1 and Lua 5.4 (gcc)
  • New tests cover nested empty containers, whitespace fallback, the
    decode_max_depth boundary, and indented encoding
  • clang -Wall -Wextra -pedantic -Werror clean
  • Differential test against master: 20,000 generated encode/decode cases
    per interpreter, no output differences
  • CI (Lua 5.1–5.4, LuaJIT, valgrind, cppcheck)

- decode: consume '}' and ']' directly instead of a full token dispatch
- encode: write "{}" directly instead of a second lua_next() scan

AI-assisted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant