Skip to content

Commit 55b3c4b

Browse files
committed
Faster strings
1 parent f8b3183 commit 55b3c4b

File tree

2 files changed

+42
-7
lines changed

2 files changed

+42
-7
lines changed

bench.js

+35
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,36 @@ const schema = {
2222
}
2323
}
2424

25+
const arraySchema = {
26+
title: 'array schema',
27+
type: 'array',
28+
items: schema
29+
}
30+
2531
const obj = {
2632
firstName: 'Matteo',
2733
lastName: 'Collina',
2834
age: 32
2935
}
3036

37+
const multiArray = [
38+
obj,
39+
obj,
40+
obj,
41+
obj,
42+
obj,
43+
obj,
44+
obj,
45+
obj,
46+
obj,
47+
obj,
48+
obj,
49+
obj,
50+
obj
51+
]
52+
3153
const stringify = require('.')(schema)
54+
const stringifyArray = require('.')(arraySchema)
3255

3356
suite.add('JSON.stringify', function () {
3457
JSON.stringify(obj)
@@ -42,6 +65,18 @@ suite.add('fast-safe-stringify', function () {
4265
safeStringify(obj)
4366
})
4467

68+
suite.add('JSON.stringify array', function () {
69+
JSON.stringify(multiArray)
70+
})
71+
72+
suite.add('fast-json-stringify array', function () {
73+
stringifyArray(multiArray)
74+
})
75+
76+
suite.add('fast-safe-stringify array', function () {
77+
safeStringify(multiArray)
78+
})
79+
4580
suite.on('complete', print)
4681

4782
suite.run()

index.js

+7-7
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,6 @@ function build (schema) {
4343
return ${main}
4444
`
4545

46-
// console.log(code)
47-
4846
return (new Function(code))()
4947
}
5048

@@ -75,17 +73,19 @@ function $asString (str) {
7573
var result = ''
7674
var last = 0
7775
var l = str.length
78-
for (var i = 0; i < l; i++) {
79-
if (str[i] === '"') {
80-
result += str.slice(last, i) + '\\"'
81-
last = i + 1
82-
}
76+
var i
77+
78+
while ((i = str.indexOf('"')) >= 0 && i < l) {
79+
result += str.slice(last, i) + '\\"'
80+
last = i + 1
8381
}
82+
8483
if (last === 0) {
8584
result = str
8685
} else {
8786
result += str.slice(last)
8887
}
88+
8989
return '"' + result + '"'
9090
}
9191

0 commit comments

Comments
 (0)