From 49e1d5ed6d3541aef5b8f42d511b838136f0a7d4 Mon Sep 17 00:00:00 2001 From: wincentj <25497140+wincentj@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:31:33 +0100 Subject: [PATCH] Add collectGraphemeIndices() as a fast method --- .changeset/floppy-chefs-warn.md | 7 +++ .gitignore | 2 + README.md | 16 +++++ benchmark/grapheme/codspeed.js | 4 ++ benchmark/grapheme/perf-collect-indices.js | 64 +++++++++++++++++++ package.json | 3 +- src/grapheme.js | 54 ++++++++++++++++ test/grapheme.js | 71 ++++++++++++++++++++++ 8 files changed, 220 insertions(+), 1 deletion(-) create mode 100644 .changeset/floppy-chefs-warn.md create mode 100644 benchmark/grapheme/perf-collect-indices.js diff --git a/.changeset/floppy-chefs-warn.md b/.changeset/floppy-chefs-warn.md new file mode 100644 index 0000000..e233f10 --- /dev/null +++ b/.changeset/floppy-chefs-warn.md @@ -0,0 +1,7 @@ +--- +"unicode-segmenter": minor +--- + +Add `collectGraphemeIndices(input, dest)` API that collects the start indices of the grapheme clusters found in the input string into the given destination array. + +This is a faster and more GC friendly version of `collectGraphemes(input)` since the input string is not split into every grapheme cluster. diff --git a/.gitignore b/.gitignore index bad2b2b..eb5cb2f 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,5 @@ lcov.info *.hermes.js *.hermes.hbc *.bundle.js + +.idea/ diff --git a/README.md b/README.md index 6a39cee..e8bd732 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,22 @@ collectGraphemes('#️⃣*️⃣0️⃣1️⃣2️⃣'); // => ["#️⃣", "*️ However, it collects all grapheme clusters at once, so it's not good for large text or streamed input. + +#### Example: Collect grapheme start indices into a reusable array + +If you only want the **start indices** of each grapheme cluster, use `collectGraphemeIndices()`, which is optimized to avoid allocations for segments and the output array. + +It populates a reusable target array in-place, returns the number of indices written, and is typically **2-4x faster** than `collectGraphemes()` and more GC friendly, so you can call it in a hot path. + +```js +import { collectGraphemeIndices } from 'unicode-segmenter/grapheme'; + +const dest = []; +const str = 'a🏳️‍🌈b'; +str.length; // => 8 +const count = collectGraphemeIndices('a🏳️‍🌈b', dest); // 3 + fills dest with [0, 1, 7] +``` + #### Example: Count graphemes If you need only the count, use `countGraphemes()`, which is optimized to avoid allocations for segments. diff --git a/benchmark/grapheme/codspeed.js b/benchmark/grapheme/codspeed.js index e4d369d..1b91377 100644 --- a/benchmark/grapheme/codspeed.js +++ b/benchmark/grapheme/codspeed.js @@ -8,12 +8,15 @@ import { countGraphemes, splitGraphemes, collectGraphemes, + collectGraphemeIndices, } from 'unicode-segmenter/grapheme'; import { testcases } from './_testcases.js'; import { corpora } from './_corpora.js'; const bench = withCodSpeed(new Bench()); +const sharedIndexBuffer = new Array(65536).fill(0); + /** * One factory per API, so that the function CodSpeed measures contains a single call and nothing else. * @@ -24,6 +27,7 @@ const apis = [ ['countGraphemes', input => () => { void countGraphemes(input); }], ['splitGraphemes', input => () => { void [...splitGraphemes(input)]; }], ['collectGraphemes', input => () => { void collectGraphemes(input); }], + ['collectGraphemeIndices', input => () => { void collectGraphemeIndices(input, sharedIndexBuffer); }], ]; /** diff --git a/benchmark/grapheme/perf-collect-indices.js b/benchmark/grapheme/perf-collect-indices.js new file mode 100644 index 0000000..5d7f796 --- /dev/null +++ b/benchmark/grapheme/perf-collect-indices.js @@ -0,0 +1,64 @@ +import { + group, + summary, + barplot, + bench, + run, + do_not_optimize, +} from 'mitata'; + +import { + splitGraphemes, + collectGraphemes, + collectGraphemeIndices, +} from '../../src/grapheme.js'; +import { testcases } from './_testcases.js'; + +// Node.js, Deno, Bun +const isSystemRuntime = typeof process === 'object' || typeof Deno === 'object' && typeof Bun === 'object'; +const isWebWorker = !isSystemRuntime && typeof self === 'object'; + +const intlSegmenter = new Intl.Segmenter(); + +const sharedIndexBuffer = new Array(65536).fill(0); + +for (const [title, input] of testcases) { + group(title, () => { + summary(() => { + barplot(() => { + bench('unicode-segmenter (collect indices)', () => { + do_not_optimize(collectGraphemeIndices(input, sharedIndexBuffer)); + }).gc('inner').baseline(true); + + bench('unicode-segmenter (collect)', () => { + do_not_optimize([...collectGraphemes(input)]); + }).gc('inner'); + + bench('unicode-segmenter (split)', () => { + do_not_optimize([...splitGraphemes(input)]); + }).gc('inner'); + + bench('Intl.Segmenter (naive)', () => { + do_not_optimize([...intlSegmenter.segment(input)].map(s => s.segment)); + }).gc('inner'); + }); + }); + }); +} + +await run({ + format: (!isWebWorker && process.env.MITATA_FORMAT) || 'mitata', + ...isWebWorker && { + colors: false, + print(s) { + self.postMessage({ type: 'log', message: s }); + }, + }, + ...isSystemRuntime && { + colors: !process.env.NO_COLOR, + }, +}); + +if (isWebWorker) { + self.postMessage({ type: 'done' }); +} diff --git a/package.json b/package.json index dc3caf9..f410a5f 100644 --- a/package.json +++ b/package.json @@ -105,7 +105,8 @@ "perf:grapheme:hermes": "node benchmark/grapheme/perf-hermes.js", "perf:grapheme:quickjs": "node benchmark/grapheme/perf-quickjs.js", "perf:grapheme-count": "node --expose-gc benchmark/grapheme/perf-count.js", - "perf:grapheme-collect": "node --expose-gc benchmark/grapheme/perf-collect.js" + "perf:grapheme-collect": "node --expose-gc benchmark/grapheme/perf-collect.js", + "perf:grapheme-collect-indices": "node --expose-gc benchmark/grapheme/perf-collect-indices.js" }, "alias": { "process": false diff --git a/src/grapheme.js b/src/grapheme.js index fdc8ce8..30fe114 100644 --- a/src/grapheme.js +++ b/src/grapheme.js @@ -436,3 +436,57 @@ export function collectGraphemes(input) { result.push(input.slice(index)); return result; } + +/** + * Collect all extended grapheme cluster start indices in the given text. + * + * Writes the start index of each grapheme cluster into `dest` and returns + * the number of indices written. Useful for zero-allocation iteration or buffer reuse. + * + * @param {string} input + * @param {number[]} dest - The destination array to write start indices into. + * @return {number} The number of graphemes (and indices written to `dest`). + * + * @example + * const dest = []; + * const str = 'a🏳️‍🌈b'; + * str.length; // => 8 + * const count = collectGraphemeIndices('a🏳️‍🌈b', dest); // 3 + fills dest with [0, 1, 7] + */ +export function collectGraphemeIndices(input, dest) { + let len = input.length; + if (len === 0) return 0; + + let cp = /** @type {number} */ (input.codePointAt(0)); + let cursor = cp > 0xFFFF ? 2 : 1; + + /** Category of the last consumed code point */ + let catBefore = cat(cp); + + /** Packed sequence state, seeded with the always-set bit 0 */ + let st = nextState(1, catBefore, cp); + + /** Start index of the current segment */ + let index = 0; + + /** how many boundary indices have been written to dest */ + let boundaryCount = 0; + + while (cursor < len) { + cp = /** @type {number} */ (input.codePointAt(cursor)); + let catAfter = cat(cp); + let boundary = !(st & PAIR[catBefore << 4 | catAfter]); + + st = nextState(st, catAfter, cp); + + if (boundary) { + dest[boundaryCount++] = index; + index = cursor; + } + cursor += cp > 0xFFFF ? 2 : 1; + catBefore = catAfter; + } + + dest[boundaryCount++] = index; + return boundaryCount; +} diff --git a/test/grapheme.js b/test/grapheme.js index 8e5b995..aa17f20 100644 --- a/test/grapheme.js +++ b/test/grapheme.js @@ -12,6 +12,7 @@ import { collectGraphemes, } from 'unicode-segmenter/grapheme'; import { assertObjectContaining } from './_helper.js'; +import {collectGraphemeIndices} from "#src/grapheme.js"; test('graphemeSegments', async t => { await t.test('empty string', () => { @@ -216,6 +217,76 @@ test('collectGraphemes', async t => { }); }); +test('collectGraphemeIndices', async t => { + await t.test('latin', () => { + /** @type {number[]} */ + const dest = []; + assert.equal(collectGraphemeIndices('abcd', dest), 4); + assert.deepEqual(dest, [0, 1, 2, 3]); + }); + + await t.test('flags', () => { + /** @type {number[]} */ + const dest = []; + assert.equal(collectGraphemeIndices('🇷🇸🇮🇴', dest), 2); + assert.deepEqual(dest, [0, 4]); + }); + + await t.test('emoji', () => { + /** @type {number[]} */ + const dest = []; + assert.equal(collectGraphemeIndices('👻👩‍👩‍👦‍👦', dest), 2); + assert.deepEqual(dest, [0, 2]); + + assert.equal(collectGraphemeIndices('🌷🎁💩😜👍🏳️‍🌈', dest), 6); + assert.deepEqual(dest, [0, 2, 4, 6, 8, 10]); + }); + + await t.test('diacritics as combining marks', () => { + /** @type {number[]} */ + const dest = []; + assert.equal(collectGraphemeIndices('Ĺo͂řȩm̅', dest), 5); + assert.deepEqual(dest, [0, 2, 4, 6, 8]); + }); + + await t.test('Jamo', () => { + /** @type {number[]} */ + const dest = []; + assert.equal(collectGraphemeIndices('가갉', dest), 2); + assert.deepEqual(dest, [0, 1]); + }); + + await t.test('Hindi', () => { + /** @type {number[]} */ + const dest = []; + assert.equal(collectGraphemeIndices('अनुच्छेद', dest), 4); + assert.deepEqual(dest, [0, 1, 3, 7]); + }); + + await t.test('demonic', () => { + /** @type {number[]} */ + const dest = []; + assert.equal(collectGraphemeIndices('Z͑ͫ̓ͪ̂ͫ̽͏̴̙̤̞͉͚̯̞̠͍A̴̵̜̰͔ͫ͗͢L̠ͨͧͩ͘G̴̻͈͍͔̹̑͗̎̅͛́Ǫ̵̹̻̝̳͂̌̌͘!͖̬̰̙̗̿̋ͥͥ̂ͣ̐́́͜͞', dest), 6); + assert.deepEqual(dest, [0, 19, 28, 34, 47, 58]); + }); + + await t.test('reuses given array', () => { + /** @type {number[]} */ + const dest = []; + + assert.equal(collectGraphemeIndices('', dest), 0); + assert.deepEqual(dest, []); + + assert.equal(collectGraphemeIndices('a🏳️‍🌈b🏳️‍🌈c', dest), 5); + assert.deepEqual(dest, [0, 1, 7, 8, 14]); + + assert.equal(collectGraphemeIndices('xa🏳️‍🌈b🏳️‍🌈c🏳️‍🌈d', dest), 8); + assert.deepEqual(dest, [0, 1, 2, 8, 9, 15, 16, 22]); + + assert.equal(collectGraphemeIndices('xya🏳️‍🌈b', dest), 5); + assert.deepEqual(dest, [0, 1, 2, 3, 9, 15, 16, 22]); + }); +}); test('conformance', async t => {