From 278132b187d4418fe8163da5e81710222f47e3f6 Mon Sep 17 00:00:00 2001 From: James Garbutt <43081j@users.noreply.github.com> Date: Tue, 27 Feb 2024 11:52:55 +0000 Subject: [PATCH] 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 --- index.js | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index 761b8b1..478d1e0 100644 --- a/index.js +++ b/index.js @@ -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} @@ -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, '.'); } /**