Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve stringify_string performance #67

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 10 additions & 42 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,52 +50,20 @@ export function get_type(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}

/** @param {string} char */
function get_escaped_char(char) {
switch (char) {
case '"':
return '\\"';
case '<':
return '\\u003C';
case '\\':
return '\\\\';
case '\n':
return '\\n';
case '\r':
return '\\r';
case '\t':
return '\\t';
case '\b':
return '\\b';
case '\f':
return '\\f';
case '\u2028':
return '\\u2028';
case '\u2029':
return '\\u2029';
default:
return char < ' '
? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`
: '';
}
}

const escape_chars = /["<\\\n\r\t\b\f\u2028\u2029\x00-\x1f]/
const u2028_all = /\u2028/g;
const u2029_all = /\u2029/g;
const lt_all = /</g;
/** @param {string} str */
export function stringify_string(str) {
let result = '';
let last_pos = 0;
const len = str.length;

for (let i = 0; i < len; i += 1) {
const char = str[i];
const replacement = get_escaped_char(char);
if (replacement) {
result += str.slice(last_pos, i) + replacement;
last_pos = i + 1;
}
if (!escape_chars.test(str)){
return `"${str}"`;
}
Comment on lines +59 to 61
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I remove this part, some test fails. But the reason is because JSON.stringify escapes more characters and uses lower case escapes (e.g. \udc00 instead of \uDC00). There should be no essential problem.
The generated string would be slightly longer but I guess that's fine because in the previous version of the tests, it was expecting the escaped ones (changed by 5530e84#diff-a561630bb56b82342bc66697aee2ad96efddcbc9d150665abd6fb7ecb7c0ab2f).


return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
return JSON.stringify(str)
.replace(u2028_all, '\\u2028')
.replace(u2029_all, '\\u2029')
.replace(lt_all, '\\u003C');
}

/** @param {Record<string | symbol, any>} object */
Expand Down