diff --git a/.changeset/orange-poems-learn.md b/.changeset/orange-poems-learn.md new file mode 100644 index 00000000..9290fb88 --- /dev/null +++ b/.changeset/orange-poems-learn.md @@ -0,0 +1,5 @@ +--- +"preact-render-to-string": patch +--- + +Improve string encoding performance by ~50% diff --git a/src/util.js b/src/util.js index 5ade429e..2396c5f8 100644 --- a/src/util.js +++ b/src/util.js @@ -3,16 +3,34 @@ export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine const ENCODED_ENTITIES = /[&<>"]/; -export function encodeEntities(input) { - const s = String(input); - if (!ENCODED_ENTITIES.test(s)) { - return s; +export function encodeEntities(str) { + // Ensure we're always parsing and returning a string: + str += ''; + + // Skip all work for strings with no entities needing encoding: + if (ENCODED_ENTITIES.test(str) === false) return str; + + let last = 0, + i = 0, + out = '', + ch = ''; + + // Seek forward in str until the next entity char: + for (; i last) out += str.slice(last, i); + out += ch; + // Start the next seek/buffer after the entity's offset: + last = i + 1; } - return s - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); + return out + str.slice(last, i); } export let indent = (s, char) =>