Skip to content

perf: write string table bytes at encode time instead of buffering each string - #121

Closed
nuzayets wants to merge 1 commit into
DataDog:mainfrom
nuzayets:string-table-encode
Closed

nuzayets wants to merge 1 commit into
DataDog:mainfrom
nuzayets:string-table-encode

Conversation

@nuzayets

Copy link
Copy Markdown
Contributor

StringTable.dedup encodes every new string into its own Uint8Array as it is added. A profile from a large Node service has thousands of distinct strings, mostly long file paths, so building its string table makes thousands of small allocations. Every array over V8's 64-byte on-heap typed array limit also gets its own off-heap backing store, which counts toward V8's external memory and can start a full GC soon after the profile is encoded.

This keeps each string's UTF-8 byte length instead and writes the bytes straight into the output buffer when the table is encoded (Buffer#write in Node, TextEncoder#encodeInto elsewhere). Strings read by decode keep a copy of their original bytes, as they do today, so re-encoding a decoded profile stays byte-for-byte identical, including bytes that aren't valid UTF-8. The public API is unchanged; _encodeString and _encodeStringFromUtf8 are kept.

Results

Node 24.22.1. Each run builds and encodes 40 string tables; times are the mean of 30 runs after 5 warm-up runs.

String tables Before After
Synthetic: 4,000 strings each, half of them pnpm-style node_modules paths (script below) 84.0 ms, 1.8 scavenges per run 41.3 ms, 0.7 scavenges per run
Same, with --scavenger-max-new-space-capacity-mb=8 (the nodejs/node#61967 workaround) 82.9 ms, 7.2 scavenges per run 40.7 ms, 2.3 scavenges per run
Taken from production wall profiles of a large Node service (~1,600 strings each), with the same flag 21.6 ms, 3.2 ms of scavenge per run 14.3 ms, 0.5 ms of scavenge per run

In the service those tables came from, _encodeStringFromUtf8 was the largest single frame in the profiler's once-a-minute serialization. For 60 of those profiles, Profile.decode(...).encode() and freshly built tables produce identical bytes before and after, with and without Buffer available.

Tests

  • Non-ASCII strings (two-, three- and four-byte characters, lone high and low surrogates, a long string) encode exactly as TextEncoder does, and encodedLength matches the encoded size.
  • A decoded string table containing invalid UTF-8 re-encodes byte for byte.
Benchmark script
// node --expose-gc bench.mjs <path to pprof-format dist>
import { PerformanceObserver, constants } from 'node:perf_hooks'
const { StringTable } = await import(`${process.argv[2]}/esm/index.js`)

const strings = []
for (let i = 0; i < 4000; i++) {
  const pkg = `pkg-${i % 300}`
  strings.push(i % 2
    ? `/srv/node_modules/.pnpm/${pkg}@1.${i % 17}.0_patch_hash=${(i * 2654435761 >>> 0).toString(16).padStart(8, '0')}${'ab'.repeat(24)}/node_modules/${pkg}/dist/lib/module-${i}.js`
    : `fn${i}${i % 5 ? 'Handler' : ''}`)
}
const run = () => {
  for (let t = 0; t < 40; t++) {
    const table = new StringTable()
    for (const s of strings) table.dedup(s)
    table.encode()
  }
}
for (let i = 0; i < 5; i++) run()
globalThis.gc()
let scavenges = 0
const obs = new PerformanceObserver((list) => {
  for (const e of list.getEntries()) if (e.detail.kind === constants.NODE_PERFORMANCE_GC_MINOR) scavenges++
})
obs.observe({ entryTypes: ['gc'] })
const N = 30
const start = process.hrtime.bigint()
for (let i = 0; i < N; i++) run()
const ms = Number(process.hrtime.bigint() - start) / 1e6 / N
await new Promise((resolve) => setTimeout(resolve, 50))
obs.disconnect()
console.log(`${ms.toFixed(1)} ms per run, ${(scavenges / N).toFixed(1)} scavenges per run`)

…ch string

StringTable encoded every new string into its own Uint8Array as it was
added. A profile with thousands of distinct file paths and function names
made thousands of small allocations, and every array over V8's 64-byte
on-heap typed array limit got its own off-heap backing store, which adds
to V8's external memory.

Track each string's UTF-8 length instead and write the bytes straight into
the output buffer when the table is encoded. Strings read by decode keep
their original bytes so re-encoding stays byte-for-byte identical.
@nuzayets

nuzayets commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Friendly ping on this one. The related serializer changes proposed in DataDog/pprof-nodejs#438 have since landed via DataDog/pprof-nodejs#430, so the string table is the remaining piece. On production string tables it cuts encode time from 21.6 ms to 14.3 ms, with byte-identical output. Happy to adjust anything.

@BridgeAR BridgeAR left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM % comment

Comment thread src/string-table.ts
this.#encodings.push(encoded)
this.#encodedLength += encoded.length
const position = this.#add(decodeString(buffer), buffer.length)
this.#decoded[position] = buffer.slice()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I am not mistaken, this could cause mistakes because slice just creates a reference.

The following would fix that by creating an actual copy and using a fast path for small entries:

Suggested change
this.#decoded[position] = buffer.slice()
this.#decoded[position] = buffer.length <= 64 || typeof Buffer === 'undefined'
? new Uint8Array(buffer)
: Buffer.from(buffer)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seconding this

Comment thread src/string-table.ts
this.#encodings.push(encoded)
this.#encodedLength += encoded.length
const position = this.#add(decodeString(buffer), buffer.length)
this.#decoded[position] = buffer.slice()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seconding this

Comment thread src/string-table.ts
if (decoded !== undefined) {
buffer.set(decoded, offset)
} else if (byteLength > 0) {
writeUtf8(this.strings[i], offset)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unlike the previous buffer.set(), both Buffer.write() and TextEncoder.encodeInto() can silently write only what fits. Since their return values are ignored, table.encode(new Uint8Array(table.encodedLength - 1)) can now return truncated protobuf output rather than throwing. Could we validate capacity in StringTable.encode(), using the existing prepareBuffer helper, restore the previous throwing behavior, and add a regression test?

@BridgeAR

Copy link
Copy Markdown
Member

Superseded by porting this including the fixes for the above. Thank you for the contribution @nuzayets!

@BridgeAR BridgeAR closed this Nov 18, 2026
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