diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 00000000000..8505a5a478d --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2026-05-20 - Optimize linesToColumns +**Learning:** Utilities that handle CLI output formatting, like `linesToColumns`, often call expensive regex-based helpers (e.g., `unstyled` for ANSI strip) multiple times for the same input. Caching these lengths in a single pass over the data significantly reduces overhead. +**Action:** Always check if string measurement utilities are called repeatedly in loops or nested maps, and use pre-calculation/caching to avoid redundant work. diff --git a/packages/cli-kit/src/public/common/string.ts b/packages/cli-kit/src/public/common/string.ts index 0e3e295df4d..a5eb847938a 100644 --- a/packages/cli-kit/src/public/common/string.ts +++ b/packages/cli-kit/src/public/common/string.ts @@ -251,16 +251,29 @@ export function tryParseInt(maybeInt: string | undefined): number | undefined { * @returns A string with the columns aligned. */ export function linesToColumns(lines: string[][]): string { + if (lines.length === 0 || !lines[0]) return '' + const widths: number[] = [] - for (let i = 0; lines[0] && i < lines[0].length; i++) { - const columnRows = lines.map((line) => line[i]!) - widths.push(Math.max(...columnRows.map((row) => unstyled(row).length))) + const unstyledLengths: number[][] = [] + + // Pre-calculate unstyled lengths and column widths in a single pass + for (let i = 0; i < lines.length; i++) { + const line = lines[i]! + unstyledLengths[i] = [] + for (let j = 0; j < line.length; j++) { + const cell = line[j]! + const length = unstyled(cell).length + unstyledLengths[i]![j] = length + widths[j] = Math.max(widths[j] ?? 0, length) + } } + const paddedLines = lines - .map((line) => { + .map((line, rowIndex) => { return line - .map((col, index) => { - return `${col}${' '.repeat(widths[index]! - unstyled(col).length)}` + .map((cell, colIndex) => { + const padding = ' '.repeat(widths[colIndex]! - unstyledLengths[rowIndex]![colIndex]!) + return `${cell}${padding}` }) .join(' ') .trimEnd()