From 4b2a7db730e6cdc3929ea5d080bfa3bf66da8e89 Mon Sep 17 00:00:00 2001 From: gonzaloriestra <14979109+gonzaloriestra@users.noreply.github.com> Date: Fri, 15 May 2026 00:52:19 +0000 Subject: [PATCH] [Performance] Optimize linesToColumns in string utilities Refactor `linesToColumns` to use a single-pass width calculation and cache unstyled lengths. This reduces calls to the expensive `unstyled` utility (which uses regex) by 50% and eliminates redundant array iterations and intermediate array creations. --- packages/cli-kit/src/public/common/string.ts | 34 +++++++++++++++----- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/packages/cli-kit/src/public/common/string.ts b/packages/cli-kit/src/public/common/string.ts index 0e3e295df4d..cc655042ace 100644 --- a/packages/cli-kit/src/public/common/string.ts +++ b/packages/cli-kit/src/public/common/string.ts @@ -251,16 +251,34 @@ export function tryParseInt(maybeInt: string | undefined): number | undefined { * @returns A string with the columns aligned. */ export function linesToColumns(lines: string[][]): string { - 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))) - } + if (lines.length === 0) return '' + + const numColumns = lines[0]!.length + const widths: number[] = new Array(numColumns).fill(0) + + // Optimization: Calculate max widths for all columns while caching unstyled lengths. + // This reduces regex-based 'unstyled' calls by 50% and avoids redundant O(Cols * Rows) array mapping. + const unstyledLengths = lines.map((line) => { + const lineLengths = new Array(line.length) + for (let i = 0; i < line.length; i++) { + const length = unstyled(line[i]!).length + lineLengths[i] = length + if (i < numColumns && length > widths[i]!) { + widths[i] = length + } + } + return lineLengths + }) + const paddedLines = lines - .map((line) => { + .map((line, rowIndex) => { + const rowLengths = unstyledLengths[rowIndex]! return line - .map((col, index) => { - return `${col}${' '.repeat(widths[index]! - unstyled(col).length)}` + .map((col, colIndex) => { + const cellWidth = rowLengths[colIndex]! + const columnWidth = widths[colIndex] ?? cellWidth + const padding = ' '.repeat(columnWidth - cellWidth) + return `${col}${padding}` }) .join(' ') .trimEnd()