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

chore(perf): asStringSmall slower than JSON.stringify #694

Closed
wants to merge 1 commit into from
Closed
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
34 changes: 1 addition & 33 deletions lib/serializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ module.exports = class Serializer {

asString (str) {
if (str.length < 42) {
return this.asStringSmall(str)
return JSON.stringify(str)
} else if (str.length < 5000 && STR_ESCAPE.test(str) === false) {
// Only use the regular expression for shorter input. The overhead is otherwise too much.
return '"' + str + '"'
Expand All @@ -113,38 +113,6 @@ module.exports = class Serializer {
return '"' + str + '"'
}

// 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
asStringSmall (str) {
const len = str.length
let result = ''
let last = -1
let point = 255

// eslint-disable-next-line
for (var i = 0; i < len; i++) {
point = str.charCodeAt(i)
if (point < 32 || (point >= 0xD800 && point <= 0xDFFF)) {
// The current character is non-printable characters or a surrogate.
return JSON.stringify(str)
}
if (
point === 0x22 || // '"'
point === 0x5c // '\'
) {
last === -1 && (last = 0)
result += str.slice(last, i) + '\\'
last = i
}
}

return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"')
}

getState () {
return this._options
}
Expand Down