Skip to content

Commit 278132b

Browse files
authored
feat: use string replaces instead of splits (#64)
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
1 parent 70e4c1b commit 278132b

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

index.js

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,16 @@ const escOpen = '\0OPEN' + Math.random() + '\0'
55
const escClose = '\0CLOSE' + Math.random() + '\0'
66
const escComma = '\0COMMA' + Math.random() + '\0'
77
const escPeriod = '\0PERIOD' + Math.random() + '\0'
8+
const escSlashPattern = new RegExp(escSlash, 'g');
9+
const escOpenPattern = new RegExp(escOpen, 'g');
10+
const escClosePattern = new RegExp(escClose, 'g');
11+
const escCommaPattern = new RegExp(escComma, 'g');
12+
const escPeriodPattern = new RegExp(escPeriod, 'g');
13+
const slashPattern = /\\\\/g;
14+
const openPattern = /\\{/g;
15+
const closePattern = /\\}/g;
16+
const commaPattern = /\\,/g;
17+
const periodPattern = /\\./g;
818

919
/**
1020
* @return {number}
@@ -19,22 +29,22 @@ function numeric (str) {
1929
* @param {string} str
2030
*/
2131
function escapeBraces (str) {
22-
return str.split('\\\\').join(escSlash)
23-
.split('\\{').join(escOpen)
24-
.split('\\}').join(escClose)
25-
.split('\\,').join(escComma)
26-
.split('\\.').join(escPeriod)
32+
return str.replace(slashPattern, escSlash)
33+
.replace(openPattern, escOpen)
34+
.replace(closePattern, escClose)
35+
.replace(commaPattern, escComma)
36+
.replace(periodPattern, escPeriod);
2737
}
2838

2939
/**
3040
* @param {string} str
3141
*/
3242
function unescapeBraces (str) {
33-
return str.split(escSlash).join('\\')
34-
.split(escOpen).join('{')
35-
.split(escClose).join('}')
36-
.split(escComma).join(',')
37-
.split(escPeriod).join('.')
43+
return str.replace(escSlashPattern, '\\')
44+
.replace(escOpenPattern, '{')
45+
.replace(escClosePattern, '}')
46+
.replace(escCommaPattern, ',')
47+
.replace(escPeriodPattern, '.');
3848
}
3949

4050
/**

0 commit comments

Comments
 (0)