Skip to content

Commit

Permalink
Performance: Avoid string-allocation on keypress with inputRule (#47094)
Browse files Browse the repository at this point in the history
While checking for inline code snippets surrounded by the backtick
we have been allocating new substrings from input strings when
looking for those characters, but we don't need to do this.

In this patch we're directly checking for the character on the input
string using string indexing and then passing the `position`
parameter to the `lastIndexOf` function so that it is able to scan
the original input string without copying it.

The performance impact of this change should be small and hard to
measure, but it should reduce pressure on the garbage collector and
be worthwhile even without clear measured results.
  • Loading branch information
dmsnell committed Feb 10, 2023
1 parent fab70c5 commit ca90b31
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions packages/format-library/src/code/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,18 @@ export const code = {
__unstableInputRule( value ) {
const BACKTICK = '`';
const { start, text } = value;
const characterBefore = text.slice( start - 1, start );
const characterBefore = text[ start - 1 ];

// Quick check the text for the necessary character.
if ( characterBefore !== BACKTICK ) {
return value;
}

const textBefore = text.slice( 0, start - 1 );
const indexBefore = textBefore.lastIndexOf( BACKTICK );
if ( start - 2 < 0 ) {
return value;
}

const indexBefore = text.lastIndexOf( BACKTICK, start - 2 );
if ( indexBefore === -1 ) {
return value;
}
Expand Down

0 comments on commit ca90b31

Please sign in to comment.