From aae5ef3f012c1d43669c81d0a14c338882901782 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Sun, 7 Mar 2021 14:16:44 +0100 Subject: [PATCH] Perf: Improve HTML entity escaping This change significantly speeds up entity ecoding making it 170 ops/sec faster than before. Benchmark: https://github.com/marko-js/isomorphic-ui-benchmarks --- server/src/util.js | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/server/src/util.js b/server/src/util.js index 349e2fe1d4..679a02e20b 100644 --- a/server/src/util.js +++ b/server/src/util.js @@ -1,21 +1,17 @@ // DOM properties that should NOT have "px" added when numeric export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|^--/i; +const HTML_ENTITY_REG = /[&<>"]/g; +const tagsToReplace = { + '&': '&', + '<': '<', + '>': '>', + '"': '"' +}; +const replaceTag = (tag) => tagsToReplace[tag] || tag; export function encodeEntities(s) { if (typeof s !== 'string') s = String(s); - let out = ''; - for (let i = 0; i < s.length; i++) { - let ch = s[i]; - // prettier-ignore - switch (ch) { - case '<': out += '<'; break; - case '>': out += '>'; break; - case '"': out += '"'; break; - case '&': out += '&'; break; - default: out += ch; - } - } - return out; + return s.replace(HTML_ENTITY_REG, replaceTag); } export let indent = (s, char) =>