From 439ae641aa5232b69d340901e23f2ee1a2d478b0 Mon Sep 17 00:00:00 2001 From: francesco Date: Mon, 22 Sep 2025 17:06:19 +0200 Subject: [PATCH 1/2] perf: simple asString close #786 Signed-off-by: francesco --- lib/serializer.js | 29 +---------------------------- 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/lib/serializer.js b/lib/serializer.js index d92a4e32..320f36b1 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -88,34 +88,7 @@ module.exports = class Serializer { } asString (str) { - const len = str.length - if (len < 42) { - // magically escape strings for json - // relying on their charCodeAt - // everything below 32 needs JSON.stringify() - // every string that contain surrogate needs JSON.stringify() - // 34 and 92 happens all the time, so we - // have a fast case for them - let result = '' - let last = -1 - let point = 255 - for (let i = 0; i < len; i++) { - point = str.charCodeAt(i) - if ( - point === 0x22 || // '"' - point === 0x5c // '\' - ) { - last === -1 && (last = 0) - result += str.slice(last, i) + '\\' - last = i - } else if (point < 32 || (point >= 0xD800 && point <= 0xDFFF)) { - // The current character is non-printable characters or a surrogate. - return JSON.stringify(str) - } - } - return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"') - } else if (len < 5000 && str.isWellFormed()) { - // Only use the regular expression for shorter input. The overhead is otherwise too much. + if (str.isWellFormed()) { return '"' + str + '"' } else { return JSON.stringify(str) From 2a2e4e4f51edba080adfc14646c67bb0b58c7fba Mon Sep 17 00:00:00 2001 From: francesco Date: Mon, 22 Sep 2025 17:11:15 +0200 Subject: [PATCH 2/2] fix: isWellFormed Signed-off-by: francesco --- lib/serializer.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lib/serializer.js b/lib/serializer.js index 320f36b1..31319ea4 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -1,5 +1,7 @@ 'use strict' +const findEscapeSequence = /["\b\t\n\v\f\r\/]/ + module.exports = class Serializer { constructor (options) { switch (options && options.rounding) { @@ -88,10 +90,10 @@ module.exports = class Serializer { } asString (str) { - if (str.isWellFormed()) { - return '"' + str + '"' - } else { + if (findEscapeSequence.test(str)) { return JSON.stringify(str) + } else { + return '"' + str + '"' } }