From 264e48b3cc2cd341ddfeaebd29378c5650adf84f Mon Sep 17 00:00:00 2001 From: Ralksta <16941050+ralksta@users.noreply.github.com> Date: Tue, 21 Apr 2026 22:51:19 +0200 Subject: [PATCH] perf: return Buffer directly instead of wrapping in Uint8Array (#131) Avoids unnecessary O(N) memory allocation and copy by returning `Buffer.from(...)` directly since Buffer inherits from Uint8Array in Node.js. Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com> --- .jules/bolt.md | 4 ++++ lib/thumbhash.ts | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.jules/bolt.md b/.jules/bolt.md index 0639513..2de2bd0 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -7,3 +7,7 @@ **Learning:** When using `Promise.all` to fetch dependent data in parallel (e.g., getting multiple subpages and standalone albums that internally call a shared `getAlbums` function), the internal cache might not be populated in time. This leads to redundant concurrent network requests to the upstream server. **Action:** Implement Promise deduplication (request coalescing) by caching the pending Promise itself (e.g., in a `this.pendingPromise` class field) rather than just the final result. Return the pending Promise to subsequent callers until it resolves, ensuring only one network request is made. +## 2024-05-29 - [Buffer inheritance optimization] + +**Learning:** `Buffer` inherits from `Uint8Array` in Node.js. Passing a `Buffer` into `new Uint8Array(...)` creates a completely new `ArrayBuffer` and copies all elements, which is an O(N) memory allocation and copy. +**Action:** When decoding base64 strings or similar byte streams in Node.js where a `Uint8Array` is expected, return `Buffer.from(data, 'base64')` directly instead of wrapping it. diff --git a/lib/thumbhash.ts b/lib/thumbhash.ts index 20a52b1..38ab106 100644 --- a/lib/thumbhash.ts +++ b/lib/thumbhash.ts @@ -27,7 +27,10 @@ function setCache(map: Map, key: K, value: V) { */ function decodeBase64(base64: string): Uint8Array { if (typeof Buffer !== 'undefined') { - return new Uint8Array(Buffer.from(base64, 'base64')); + // ⚡ Bolt: Return Buffer directly instead of wrapping in new Uint8Array. + // Buffer inherits from Uint8Array, so returning it directly prevents + // unnecessary memory allocation and copying. + return Buffer.from(base64, 'base64'); } return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)); }