Skip to content

perf(string): literal-prefix memchr scan and tighter dispatch in the Lua pattern engine - #68

Merged
esrrhs merged 1 commit into
masterfrom
cursor/lua-pattern-engine-perf-9ad9
Dec 1, 2026
Merged

esrrhs merged 1 commit into
masterfrom
cursor/lua-pattern-engine-perf-9ad9

Conversation

@esrrhs

@esrrhs esrrhs commented Dec 1, 2026

Copy link
Copy Markdown
Owner

What changed

Optimizes the shared Lua 5.4 pattern engine (src/native/string/lua_pattern.cpp, .h) that backs string.find / string.match / string.gmatch / string.gsub on all three backends. Three changes, per the iteration plan:

  1. Literal-prefix fast scan. Search computes the length of the pattern's leading fixed literal prefix (LiteralPrefixLen), then uses memchr on the first literal byte plus a memcmp prefix filter before entering the matcher, instead of stepping every subject byte through the full match routine. Pure-literal patterns resolve to a single memcmp in both Search and MatchAt (the latter covers gmatch/gsub's per-position calls). Quantifier rules match lstrlib.c (a+ keeps a 1-byte prefix, a*/a?/a- don't; leading *+?- are literals).
  2. Tighter class/set dispatch. %a..%z membership is now a startup-built 256-bit bitmap per class (same ctype results as the previous per-byte switch), and the quantifier loops (MaxExpand/MinExpand) compile the repeated item once into an ItemBits bitmap instead of re-parsing the set/class per byte. CompileItem mirrors SingleMatchByte's set parsing exactly (leading-] member, ranges, %-escapes, negation).
  3. Bounded capture copies. Capture snapshots (SaveCaps/RestoreCaps) copy only the first level_ entries instead of the full 32-entry array, and Capture/MatchResult drop redundant zero-initialization on the hot path (only the first level entries are ever read; all external readers are level-bounded).

Also adds a bench_string_find_literal micro-benchmark (pattern-mode find of a literal, correctness-verified each iteration against the C++ result) and fixes a stale "ECMAScript" comment in benchmark/benchmark_string.cpp.

Semantics: byte-exact, verified three ways

  • Engine differential (old vs new): extracted master's engine and ran it side-by-side with the new one on ~18.5M randomized find/match cases (random subjects/patterns incl. embedded NUL, %f[set], %bxy, lazy -, position captures): 0 mismatches; 1.5M of those under ASan+UBSan, clean.
  • Lua-level differential vs PUC-Rio Lua 5.4.8: 200k deterministic random cases × 6 operations (find, find+init, match, match+init, gmatch, gsub) = 1.2M ops, output compared line-by-line. Only 3 lines differ, all one pre-existing deviation: fakelua's string.find lacks PUC's nospecials plain-search shortcut (PUC's SPECIALS excludes )), so a pattern like 10) errors in fakelua ("invalid pattern capture") where PUC plain-searches. Present identically in master; the engine itself agrees with PUC everywhere including erroring on bare ) in match/gmatch/gsub. Left unchanged (out of this slice); flagging as a possible follow-up.
  • Tests: all 69 test_string.* gtests pass on all three backends (incl. test_string_lua_pattern.lua, test_gsub_negative_n.lua). Full suite: 1835/1858 pass; the 23 failures are all test_mysql/test_redis integration tests that need live MySQL/Redis services (unavailable in this VM: "Can't connect to server on 127.0.0.1"). The differential fuzz target was not run: fuzz/build_fuzz.sh requires a GCC 15 toolchain at /root/GCC-15 that this environment doesn't have; the ASan/UBSan differential harness above covered the same ground.

Benchmarks (measured on this VM, 4-core, core-pinned, Release)

Branch vs master baseline, same machine, both runs back-to-back; PUC-Lua rows stable within 1.00–1.07x between runs.

fakelua branch vs master (speedup):

benchmark TCC GCC INTERP
StringGsub/10 1.63x 1.71x 1.64x
StringGsub/100 2.66x 2.77x 2.75x
StringGsub/1000 3.19x 2.84x 3.26x
StringGmatch/1000 ([0-9]+) 1.81x 2.00x 1.66x
StringFindPattern/1000 ([0-9]+ loop) 1.16x 1.16x 1.15x
StringFind (plain=true) ~1.0x ~1.0x ~1.0x

(plain=true find doesn't touch the pattern engine; 0.95–1.05x is run noise.)

vs PUC-Rio Lua 5.4.8 on the branch (time ratio, <1 means fakelua faster):

benchmark TCC GCC INTERP
StringGsub/1000 0.74x 0.83x 0.73x (was ~2.3x slower)
StringGmatch/1000 1.29x 0.99x 1.63x (was 2.69x)
StringFindPattern/1000 2.71x 2.46x 2.74x (was 3.14x)

StringFindPattern (a string.find-with-init loop) is improved but still slower than PUC Lua — per-call engine entry overhead dominates; noted for a future slice.

New StringFindLiteral benchmark (pattern-mode find of needle in an a-haystack, no master equivalent): INTERP 290→524 ns and GCC 269→493 ns across sizes 10→10000 (near-flat thanks to memchr), vs PUC Lua 109→893 ns — fakelua is faster than PUC at 10000 (524 vs 893 ns). In the isolated -O3 engine harness, the literal find in a 10KB subject is ~448x vs the old engine; end-to-end it's diluted by VM call overhead.

Isolated engine-harness (old vs new engine, -O3, no VM): find [0-9]+ 1.71x, gmatch-style [0-9]+ 2.69x, gsub-style literal MatchAt 2.53x.

Open in Web Open in Cursor 

…Lua pattern engine

- Search: memchr on the first literal byte plus a memcmp prefix filter
  before entering the matcher; pure-literal patterns resolve to a single
  memcmp (MatchAt and Search), mirroring PUC-Rio's memchr-based plain
  scan while staying in pattern semantics.
- Class/set dispatch: startup-built 256-bit membership bitmaps for the
  %a..%z classes (same ctype results as before), and quantifier loops
  (max/min_expand) compile the repeated item once into a bitmap instead
  of re-parsing the set per byte.
- Capture snapshots copy only the first level_ entries instead of the
  full 32-entry array, and MatchResult/Capture drop redundant zero
  init on the hot path.

Semantics are byte-exact with the previous engine: verified with a
differential harness that runs the old and new engine side by side on
~18.5M randomized cases (0 mismatches, clean under ASan/UBSan), plus a
200k-case Lua-level differential against PUC-Rio Lua 5.4.8 over
find/match/gmatch/gsub.

Co-authored-by: esrrhs <esrrhs@163.com>
@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 95.20000% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.55%. Comparing base (45d065d) to head (4390559).

Files with missing lines Patch % Lines
src/native/string/lua_pattern.cpp 95.20% 6 Missing ⚠️
❗ Your organization needs to install the Codecov GitHub app to enable full functionality.
Additional details and impacted files
@@            Coverage Diff             @@
##           master      #68      +/-   ##
==========================================
- Coverage   94.56%   94.55%   -0.01%     
==========================================
  Files         129      130       +1     
  Lines       32349    32425      +76     
==========================================
+ Hits        30590    30661      +71     
- Misses       1759     1764       +5     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@esrrhs
esrrhs merged commit 358697f into master Dec 1, 2026
9 checks passed
@esrrhs
esrrhs deleted the cursor/lua-pattern-engine-perf-9ad9 branch December 1, 2026 07:12
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.

3 participants