Skip to content

perf(bitap): reuse bit arrays and look up the alphabet by char code - #865

Closed
tunardev wants to merge 1 commit into
krisk:mainfrom
tunardev:perf/bitap-typed-arrays
Closed

tunardev wants to merge 1 commit into
krisk:mainfrom
tunardev:perf/bitap-typed-arrays

Conversation

@tunardev

Copy link
Copy Markdown
Contributor

Summary

Up to ~1.9x faster fuzzy search. search() allocated a new array for every error level of every text, and read each character as a one-character string to look it up in the alphabet. This PR reuses two typed arrays and looks characters up by char code.

Benchmarks

20k docs (faker), keys title, author, tags, default options. Median of 7 runs, Node 25:

query main this PR speedup
chair 131.2ms 95.0ms 1.38x
grnite 150.8ms 108.2ms 1.39x
Ergonomic Steel 484.3ms 256.5ms 1.89x
frsh tuna 255.7ms 152.7ms 1.67x
xq 54.7ms 45.0ms 1.22x

Longer queries gain more, because they run more error levels per text.

What changed

  • search() reuses two module-level Int32Arrays and swaps them between error levels. It grows them when a longer text comes in, and zero-fills the part each level reads, so unwritten slots still read as 0 like undefined did.
  • createPatternAlphabet() keys the alphabet by charCodeAt, and search() reads text with text.charCodeAt(i).

Correctness

All 543 tests pass and lint is clean. Results are the same as main (JSON.stringify of the output) for 66 option and query combinations: includeMatches, minMatchCharLength, ignoreLocation, findAllMatches, isCaseSensitive, ignoreDiacritics, weighted keys, patterns over 32 characters, and CJK and accented text. New test/bitap-buffers.test.js covers reusing the arrays between long and short texts, texts longer than the first buffer, and non-Latin characters.

@krisk krisk closed this in 0d691dc Nov 22, 2026
@krisk

krisk commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Landed in 0d691dc, and this is a great one. Thank you! I benchmarked it against main with alternating runs and got 1.5-2x on fuzzy search and up to 2.4x on token search, with the non-Bitap paths unchanged. A differential run of a few thousand random searches across option combinations came back identical to main.

One change on top in 830626a. The shared arrays grew to fit the longest text ever searched and never shrank, so a single 5M-character document kept 67 MB alive for the life of the process. Reuse is now capped at 64k entries and longer texts get one-off arrays, which keeps the speedup for normal text and caps retained memory at about 512 KB.

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.

2 participants