Skip to content

Commit

Permalink
Performance - Drastically improve worst case regex performance
Browse files Browse the repository at this point in the history
Converting from array to string repeatedly in a loop leads to
very poor performance in some contexts.
  • Loading branch information
adam-arthur committed Jan 18, 2023
1 parent 99ada39 commit 2cbdcae
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ const wrapWord = (rows, word, columns) => {
}

if (ESCAPES.has(character)) {
const ansiEscapeLinkCandidate = characters.slice(index + 1, index + 1 + ANSI_ESCAPE_LINK.length).join('');
isInsideEscape = true;
isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);
isInsideLinkEscape = ansiEscapeLinkCandidate === ANSI_ESCAPE_LINK;
}

if (isInsideEscape) {
Expand Down Expand Up @@ -164,13 +165,17 @@ const exec = (string, columns, options = {}) => {
rows = rows.map(row => stringVisibleTrimSpacesRight(row));
}

const pre = [...rows.join('\n')];
const preString = rows.join('\n');
const pre = [...preString];

// Account for unicode characters with length 2
let preStringIndex = 0;

for (const [index, character] of pre.entries()) {
returnValue += character;

if (ESCAPES.has(character)) {
const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};
const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(preString.slice(preStringIndex)) || {groups: {}};
if (groups.code !== undefined) {
const code = Number.parseFloat(groups.code);
escapeCode = code === END_CODE ? undefined : code;
Expand Down Expand Up @@ -198,6 +203,8 @@ const exec = (string, columns, options = {}) => {
returnValue += wrapAnsiHyperlink(escapeUrl);
}
}

preStringIndex += character.length;
}

return returnValue;
Expand Down

0 comments on commit 2cbdcae

Please sign in to comment.