Skip to content

Commit 3a38d56

Browse files
committed
perf(index): store index records in columns
FuseIndex keeps records in typed-array columns (one row per record, one per field value) instead of one object per record and per value. Text values stay references to the documents' own strings; norms are ids into a table of exact values. Scores, ordering and toJSON() output are unchanged (differential vs 7.6.0-beta.4: 8,400 randomized searches and 2,557 toJSON comparisons, zero differences). Base index memory at 100k items: objects 69.6 MB -> 12.0 MB (-83%), strings 7.2 MB -> 3.4 MB (-52%); objects with token search 81.4 MB -> 23.8 MB. Search is equal or faster, object builds equal or faster, removeAt/remove 4-17% faster. Loading a saved index (parseIndex) is 13-33% slower since records are converted into columns, and string-list builds are ~6-8% slower at 100k (+0.7 ms). Behavior changes: - FuseIndex.records is deprecated (removed in v8). It returns a fresh, detached snapshot in the old shape on each access; writing to it no longer affects search. Dev builds warn once. - toJSON() builds its output from the columns instead of returning the live record array. - add() returns a detached record; records passed to setIndexRecords() or assigned to records are copied in. - parseIndex()/setIndexRecords() reject records whose document indexes, field keys or array positions aren't integers in 0..2^31-1. Tests updated for the detached snapshot: "FuseIndex.removeAt handles unsorted records" now loads the reordered records via setIndexRecords(), and the token-search removal test asserts that editing a snapshot changes neither search nor removal.
1 parent e587382 commit 3a38d56

21 files changed

Lines changed: 3517 additions & 915 deletions

‎bench/columnar-shape.mjs‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// Columnar index shape check: base index memory (heap + ArrayBuffers) for the
2+
// record layout vs the columnar layout, and that the deprecated `records`
3+
// snapshot is not retained once dropped.
4+
//
5+
// node bench/columnar-shape.mjs
6+
//
7+
// The record layout is the `records` snapshot: the exact shape pre-columnar
8+
// versions held, sharing the documents' strings as they did (the index that
9+
// produced it is released). Each representation is built inside a function
10+
// whose frame exits before measuring, so V8 can't keep the previous one alive.
11+
12+
import v8 from 'node:v8'
13+
import vm from 'node:vm'
14+
import Fuse from '../dist/fuse.mjs'
15+
import { random } from './rng.mjs'
16+
17+
v8.setFlagsFromString('--expose-gc')
18+
const gc = vm.runInNewContext('gc')
19+
console.warn = () => {}
20+
21+
const SIZE = 100_000
22+
const words =
23+
'apple banana cherry search fuzzy index query javascript typescript optimization performance library matching string pattern location distance threshold score result ranking token document field record value design system data model network server client browser render cache memory'.split(
24+
' '
25+
)
26+
const pick = () => words[Math.floor(random() * words.length)]
27+
const sentence = (n) => Array.from({ length: n }, pick).join(' ')
28+
29+
const shapes = {
30+
objects: {
31+
keys: ['title', 'body', 'tags'],
32+
docs: Array.from({ length: SIZE }, () => ({
33+
title: sentence(3 + Math.floor(random() * 5)),
34+
body: sentence(15 + Math.floor(random() * 25)),
35+
tags: [pick(), pick(), pick()]
36+
}))
37+
},
38+
strings: {
39+
keys: [],
40+
docs: Array.from({ length: SIZE }, () =>
41+
sentence(3 + Math.floor(random() * 6))
42+
)
43+
}
44+
}
45+
46+
const used = () => {
47+
gc()
48+
gc()
49+
const { heapUsed, arrayBuffers } = process.memoryUsage()
50+
return heapUsed + arrayBuffers
51+
}
52+
53+
const median = (values) => [...values].sort((a, b) => a - b)[values.length >> 1]
54+
55+
// Memory retained by whatever build() returns, median of 3.
56+
const retainedBy = (build) => {
57+
const deltas = []
58+
let kept = null
59+
for (let i = 0; i < 3; i += 1) {
60+
kept = null
61+
const before = used()
62+
kept = build()
63+
deltas.push(used() - before)
64+
}
65+
if (!kept) throw new Error('unreachable')
66+
return median(deltas)
67+
}
68+
69+
const mb = (bytes) => `${(bytes / 1e6).toFixed(2)}MB`
70+
71+
for (const [name, { keys, docs }] of Object.entries(shapes)) {
72+
const records = () => Fuse.createIndex(keys, docs).records
73+
const columnar = () => Fuse.createIndex(keys, docs)
74+
75+
const recordBytes = retainedBy(records)
76+
const columnarBytes = retainedBy(columnar)
77+
const saving = 1 - columnarBytes / recordBytes
78+
console.log(
79+
` ${name} ${SIZE.toLocaleString('en-US')} records: median=${mb(recordBytes)}`
80+
)
81+
console.log(
82+
` ${name} ${SIZE.toLocaleString('en-US')} columnar: median=${mb(columnarBytes)}` +
83+
` (${(saving * 100).toFixed(0)}% less)`
84+
)
85+
86+
// The snapshot costs memory only while it is held.
87+
let index = Fuse.createIndex(keys, docs)
88+
const base = used()
89+
let snapshot = index.records
90+
const holding = used() - base
91+
snapshot = null
92+
const after = used() - base
93+
console.log(
94+
` ${name} snapshot held: ${mb(holding)}, after release: ${mb(after)}` +
95+
(after > holding / 10 ? ' <-- snapshot retained!' : '')
96+
)
97+
index = null
98+
void snapshot
99+
void index
100+
}

0 commit comments

Comments
 (0)