From fa7c5f9a19453db8d310097053659a6b6e304ad1 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Wed, 2 Dec 2026 23:00:40 -0500 Subject: [PATCH 1/2] perf: reuse encoder and views in element info lookups --- .changeset/element-info-allocations.md | 5 +++++ term-native.ts | 19 +++++++++++++------ 2 files changed, 18 insertions(+), 6 deletions(-) create mode 100644 .changeset/element-info-allocations.md diff --git a/.changeset/element-info-allocations.md b/.changeset/element-info-allocations.md new file mode 100644 index 0000000..d2b30c2 --- /dev/null +++ b/.changeset/element-info-allocations.md @@ -0,0 +1,5 @@ +--- +"@bomb.sh/tty": patch +--- + +Improves `result.info.get()` performance by reusing the encoder and memory views across lookups instead of allocating per call diff --git a/term-native.ts b/term-native.ts index f3d79ec..057a789 100644 --- a/term-native.ts +++ b/term-native.ts @@ -223,6 +223,10 @@ export async function createTermNative( layout(w, h); setCaps(caps); + let encoder = new TextEncoder(); + let transfer = new Uint8Array(memory.buffer, opsBuf, transferBytes); + let view = new DataView(memory.buffer); + return { memory, get statePtr() { @@ -284,20 +288,23 @@ export async function createTermNative( getElementInfo( id: string, ): { bounds: BoundingBox; replay: Op } | undefined { - let enc = new TextEncoder(); - let bytes = enc.encode(id); + // Replay lookups run once per unchanged sibling, so reuse the encoder and + // views instead of allocating per call. Growth detaches the old buffer. + if (transfer.buffer !== memory.buffer || transfer.byteOffset !== opsBuf) { + transfer = new Uint8Array(memory.buffer, opsBuf, transferBytes); + view = new DataView(memory.buffer); + } // Native code consumes the name before writing the result, so the query // and metadata share storage even when the name fills the workspace. let out = opsBuf; - if (bytes.length > transferBytes) { + let { read, written } = encoder.encodeInto(id, transfer); + if (read < id.length) { return undefined; } - new Uint8Array(memory.buffer).set(bytes, opsBuf); - let found = ct.get_element_info(statePtr!, opsBuf, bytes.length, out); + let found = ct.get_element_info(statePtr!, opsBuf, written, out); if (!found) { return undefined; } - let view = new DataView(memory.buffer); return { bounds: { x: view.getFloat32(out + BOUNDING_BOX.x, true), From cb05949db61aac55b19bf7b9bd15d9a51859b359 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Wed, 2 Dec 2026 23:33:04 -0500 Subject: [PATCH 2/2] perf: encode packed strings in place --- .changeset/element-info-allocations.md | 2 +- ops.ts | 46 +++++++++++++++++++------- test/pack.test.ts | 21 ++++++++++++ 3 files changed, 56 insertions(+), 13 deletions(-) diff --git a/.changeset/element-info-allocations.md b/.changeset/element-info-allocations.md index d2b30c2..7290af7 100644 --- a/.changeset/element-info-allocations.md +++ b/.changeset/element-info-allocations.md @@ -2,4 +2,4 @@ "@bomb.sh/tty": patch --- -Improves `result.info.get()` performance by reusing the encoder and memory views across lookups instead of allocating per call +Improves `term.render()` and `result.info.get()` memory use by encoding element ids and text directly into the transfer buffer instead of allocating per string diff --git a/ops.ts b/ops.ts index 7c16a00..fd80dea 100644 --- a/ops.ts +++ b/ops.ts @@ -117,13 +117,15 @@ function sideBg( function packString( view: DataView, bytes: Uint8Array, + str: string, o: number, end: number, context: string, ): number { - let paddedLength = Math.ceil(bytes.length / 4) * 4; - let next = o + 4 + paddedLength; - if (next > end) { + let start = o + 4; + let length = encodeAt(bytes, str, start, end); + if (length < 0 || start + Math.ceil(length / 4) * 4 > end) { + let next = start + Math.ceil(encoder.encode(str).length / 4) * 4; throw new RangeError( `transfer buffer capacity exceeded while packing ${context} ` + `(${next} byte offset, ${end} byte limit). ` + @@ -131,11 +133,32 @@ function packString( ); } - view.setUint32(o, bytes.length, true); - o += 4; - new Uint8Array(view.buffer).set(bytes, o); - o += paddedLength; - return o; + view.setUint32(o, length, true); + return start + Math.ceil(length / 4) * 4; +} + +/** + * Encode `str` as UTF-8 into `bytes` at `at`, returning the byte length, or -1 + * when it does not fit before `end`. Encoding in place avoids the native + * backing store `encode()` allocates per string, which only a GC frees. + */ +function encodeAt( + bytes: Uint8Array, + str: string, + at: number, + end: number, +): number { + // ASCII, the common case for ids and text, needs no encoder. + for (let i = 0; i < str.length; i++) { + let code = str.charCodeAt(i); + if (code > 0x7f) { + let rest = encoder.encodeInto(str.slice(i), bytes.subarray(at + i, end)); + return rest.read < str.length - i ? -1 : i + rest.written; + } + if (at + i >= end) return -1; + bytes[at + i] = code; + } + return str.length; } export function pack( @@ -145,6 +168,7 @@ export function pack( limit?: number, ): number { let view = new DataView(mem); + let bytes = new Uint8Array(mem); let end = limit ?? mem.byteLength; let o = offset; @@ -159,8 +183,7 @@ export function pack( view.setUint32(o, OP_OPEN_ELEMENT, true); o += 4; - let bytes = encoder.encode(op.id); - o = packString(view, bytes, o, end, "element id"); + o = packString(view, bytes, op.id, o, end, "element id"); // §8.5: currentcolor as an element's own color inherits, exactly // like omitting it, so neither writes a color group. @@ -364,8 +387,7 @@ export function pack( view.setUint32(o, op.caret ?? 0xFFFFFFFF, true); o += 4; - let str = encoder.encode(op.content); - o = packString(view, str, o, end, "text content"); + o = packString(view, bytes, op.content, o, end, "text content"); break; } } diff --git a/test/pack.test.ts b/test/pack.test.ts index 775617a..d41aa86 100644 --- a/test/pack.test.ts +++ b/test/pack.test.ts @@ -34,6 +34,27 @@ describe("pack", () => { ); }); + it("packs ids and text as length-prefixed UTF-8", () => { + let encoder = new TextEncoder(); + for ( + let content of ["ascii", "café", "日本語", "a🙂b", "cafe\u0301", ""] + ) { + let memory = new ArrayBuffer(256); + pack([open(content), close()], memory, 0, memory.byteLength); + let view = new DataView(memory); + let expected = encoder.encode(content); + expect(view.getUint32(4, true)).toBe(expected.length); + expect(new Uint8Array(memory, 8, expected.length)).toEqual(expected); + } + }); + + it("throws a descriptive RangeError when multibyte text exceeds the transfer buffer", () => { + // Fits as UTF-16 code units but not as UTF-8 bytes. + let memory = new ArrayBuffer(32); + expect(() => pack([text("日".repeat(8))], memory, 0, memory.byteLength)) + .toThrow(/transfer buffer capacity exceeded while packing text content/); + }); + it("throws a descriptive RangeError when an element id exceeds the transfer buffer", () => { let memory = new ArrayBuffer(16); let error: unknown;