From 5e3710da41f882cee9445b41215fe131c4368d2c Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 18 Feb 2026 12:07:08 +0000 Subject: [PATCH] =?UTF-8?q?perf:=20replace=20O(n=C2=B2)=20string=20concate?= =?UTF-8?q?nation=20with=20chunked=20approach=20in=20arrayBufferToBase64?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous implementation built a binary string by appending one character at a time (binary += String.fromCharCode(bytes[i])), which is O(n²) for large buffers because JavaScript strings are immutable and each += creates a new string copy. The new implementation processes the buffer in 8 KB chunks using String.fromCharCode.apply() and joins them once at the end, reducing the operation to O(n) and significantly improving performance for image payloads (which can be up to 2 MB). Co-Authored-By: 396217818@qq.com <396217818@qq.com> --- backend/utils/base64.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/backend/utils/base64.js b/backend/utils/base64.js index 1572c56..6b651cd 100644 --- a/backend/utils/base64.js +++ b/backend/utils/base64.js @@ -1,9 +1,11 @@ export function arrayBufferToBase64(buffer) { - let binary = ""; const bytes = new Uint8Array(buffer); const len = bytes.byteLength; - for (let i = 0; i < len; i++) { - binary += String.fromCharCode(bytes[i]); + const chunkSize = 8192; + const parts = []; + for (let i = 0; i < len; i += chunkSize) { + const slice = bytes.subarray(i, Math.min(i + chunkSize, len)); + parts.push(String.fromCharCode.apply(null, slice)); } - return btoa(binary); + return btoa(parts.join("")); }