Skip to content

Commit

Permalink
feat: use string replaces instead of splits (#64)
Browse files Browse the repository at this point in the history
Using a split/join results in a lot of garbage collection for the unused
arrays, along with being fairly slow. This just moves to using a RegExp
replace instead.

Bench result:
> 3,410 ops/sec

Bench result on main:
> 1,150 ops/sec
  • Loading branch information
43081j committed Feb 27, 2024
1 parent 70e4c1b commit 278132b
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ const escOpen = '\0OPEN' + Math.random() + '\0'
const escClose = '\0CLOSE' + Math.random() + '\0'
const escComma = '\0COMMA' + Math.random() + '\0'
const escPeriod = '\0PERIOD' + Math.random() + '\0'
const escSlashPattern = new RegExp(escSlash, 'g');
const escOpenPattern = new RegExp(escOpen, 'g');
const escClosePattern = new RegExp(escClose, 'g');
const escCommaPattern = new RegExp(escComma, 'g');
const escPeriodPattern = new RegExp(escPeriod, 'g');
const slashPattern = /\\\\/g;
const openPattern = /\\{/g;
const closePattern = /\\}/g;
const commaPattern = /\\,/g;
const periodPattern = /\\./g;

/**
* @return {number}
Expand All @@ -19,22 +29,22 @@ function numeric (str) {
* @param {string} str
*/
function escapeBraces (str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod)
return str.replace(slashPattern, escSlash)
.replace(openPattern, escOpen)
.replace(closePattern, escClose)
.replace(commaPattern, escComma)
.replace(periodPattern, escPeriod);
}

/**
* @param {string} str
*/
function unescapeBraces (str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.')
return str.replace(escSlashPattern, '\\')
.replace(escOpenPattern, '{')
.replace(escClosePattern, '}')
.replace(escCommaPattern, ',')
.replace(escPeriodPattern, '.');
}

/**
Expand Down

0 comments on commit 278132b

Please sign in to comment.