Skip to content

Commit e4ea125

Browse files
authored
Merge pull request #18 from fastify/restore-obj-speed
Revert "Replaced asString with JSON.stringify"
2 parents bbc3522 + b5b3f97 commit e4ea125

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

index.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ function build (schema, options) {
1515
`
1616
code += `
1717
${$asString.toString()}
18+
${$asStringSmall.toString()}
1819
${$asNumber.toString()}
1920
${$asNull.toString()}
2021
${$asBoolean.toString()}
@@ -83,7 +84,36 @@ function $asString (str) {
8384
str = str.toString()
8485
}
8586

86-
return JSON.stringify(str)
87+
if (str.length < 42) {
88+
return $asStringSmall(str)
89+
} else {
90+
return JSON.stringify(str)
91+
}
92+
}
93+
94+
// magically escape strings for json
95+
// relying on their charCodeAt
96+
// everything below 32 needs JSON.stringify()
97+
// 34 and 92 happens all the time, so we
98+
// have a fast case for them
99+
function $asStringSmall (str) {
100+
var result = ''
101+
var last = 0
102+
var l = str.length
103+
var point = 255
104+
for (var i = 0; i < l && point >= 32; i++) {
105+
point = str.charCodeAt(i)
106+
if (point === 34 || point === 92) {
107+
result += str.slice(last, i) + '\\' + str[i]
108+
last = i + 1
109+
}
110+
}
111+
if (last === 0) {
112+
result = str
113+
} else {
114+
result += str.slice(last)
115+
}
116+
return point < 32 ? JSON.stringify(str) : '"' + result + '"'
87117
}
88118

89119
function addPatternProperties (schema, externalSchema) {

0 commit comments

Comments
 (0)