From 004a3dfdc07a25fc31848230bba590014c4d7bd7 Mon Sep 17 00:00:00 2001 From: ightevenmckane187 <214069160+ightevenmckane187@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:17:57 +0000 Subject: [PATCH] perf(persistence): direct string HMAC update and single output allocation - Pass JSON string payload directly to `crypto.createHmac.update(payload, 'utf8')` - Eliminate intermediate `Buffer.from(payload)` allocations - Allocate single output buffer and write payload directly using `out.write` - Use `Buffer.alloc` to prevent uninitialized heap memory leak hazards --- src/os/persistence/PersistenceLayer.ts | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/src/os/persistence/PersistenceLayer.ts b/src/os/persistence/PersistenceLayer.ts index b60a349..ec4b32d 100644 --- a/src/os/persistence/PersistenceLayer.ts +++ b/src/os/persistence/PersistenceLayer.ts @@ -8,28 +8,18 @@ const SIGNATURE_LENGTH = 32; export class PersistenceLayer { /** * Bolt Optimization: Explicitly typed as Buffer. - * Constructs output buffer using Buffer.allocUnsafe() with manual .set() and .write() copying, - * which is significantly faster (~15%) than Buffer.concat() and avoids multiple buffer allocations. + * Computes HMAC directly on string payload and writes directly to pre-allocated buffer + * using Buffer.alloc to eliminate uninitialized memory leak hazards while avoiding extra allocations. */ save(data: any, key: string): Buffer { const payload = JSON.stringify(data); - const payloadBuf = Buffer.from(payload, 'utf8'); - - // Bolt Optimization: Allocate unsafe buffer for exact combined size to avoid Buffer.concat and intermediate payload allocations - const outBuf = Buffer.allocUnsafe(38 + payloadBuf.length); - - // Copy pre-allocated header and payload - outBuf.set(HEADER_BUF, 0); - outBuf.set(payloadBuf, 38); + const payloadByteLength = Buffer.byteLength(payload, 'utf8'); - // Compute and write HMAC signature directly - const hmac = crypto.createHmac('sha256',. key); - hmac.update(payloadBuf); + const hmac = crypto.createHmac('sha256', key); + hmac.update(payload, 'utf8'); const signature = hmac.digest(); - outBuf.set(signature, 6); - const payloadByteLength = Buffer.byteLength(payload, 'utf8'); - const out = Buffer.allocUnsafe(HEADER_LENGTH + SIGNATURE_LENGTH + payloadByteLength); + const out = Buffer.alloc(HEADER_LENGTH + SIGNATURE_LENGTH + payloadByteLength); // Zero-copy set of pre-allocated header out.set(HEADER_MAGIC, 0);