diff --git a/.jules/bolt.md b/.jules/bolt.md index edb687422..fda30e6a0 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -5,3 +5,7 @@ ## 2026-10-15 - [Performance] Prevent unnecessary UI array recalculations **Learning:** In the chat component (`useThreadList`), derived state that requires filtering and sorting large arrays (like generating nested agent lists) was running synchronously on every render. Given that chat polling triggers frequent re-renders, this caused unnecessary CPU strain on lists that only rarely change. **Action:** Use `useMemo` for derived states like `rows` and `current` in custom hooks when they involve `.filter()`, `.map()`, or `.sort()` and depend on data that updates less frequently than the component renders. + +## 2025-02-23 - Optimizing Large Array Serialization in Preact Components +**Learning:** In Preact components, deriving state on hot paths (like `CodeBlock`) using nested `.map().join()` operations creates unnecessary intermediate array allocations, causing memory pressure and CPU overhead from garbage collection when dealing with large datasets (e.g. string concatenation of large code blocks). +**Action:** Wrap expensive derived states in `useMemo` and replace `.map().join()` with manual `for` loops. This prevents intermediate allocations and significantly reduces overhead during render loops. diff --git a/apps/web/src/components/chat/CodeBlock.tsx b/apps/web/src/components/chat/CodeBlock.tsx index a86bfe958..c50cc8de2 100644 --- a/apps/web/src/components/chat/CodeBlock.tsx +++ b/apps/web/src/components/chat/CodeBlock.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'preact/hooks'; +import { useEffect, useRef, useState, useMemo } from 'preact/hooks'; import { Check, Copy } from 'lucide-preact'; import { copyText } from '../../lib/clipboard'; import { highlightCode, normalizeLang, type CodeToken } from '../../lib/highlight'; @@ -26,7 +26,24 @@ export function CodeBlock({ code, lang }: { code: string; lang?: string }) { window.clearTimeout(t); }; }, [code, lang]); - const shown = tokens && tokens.map((l) => l.map((t) => t.content).join('')).join('\n') === code ? tokens : null; + + // Performance optimization: Avoid intermediate array allocations for large code blocks. + // We use useMemo and manual `for` loops instead of nested `.map().join()` chains + // to reduce memory allocations and CPU overhead during hot path renders. + const shown = useMemo(() => { + if (!tokens) return null; + let text = ""; + for (let i = 0; i < tokens.length; i++) { + const line = tokens[i]; + for (let j = 0; j < line.length; j++) { + text += line[j].content; + } + if (i < tokens.length - 1) { + text += '\n'; + } + } + return text === code ? tokens : null; + }, [tokens, code]); async function onCopy() { const ok = await copyText(code);