Skip to content

Commit c59fa7f

Browse files
committed
add benchmarks for JTD serializers to compare with JSON.stringify
1 parent d5d1b7c commit c59fa7f

File tree

3 files changed

+81
-1
lines changed

3 files changed

+81
-1
lines changed

benchmark/package.json

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"private": true,
3+
"devDependencies": {
4+
"benchmark": "^2.1.4"
5+
}
6+
}

benchmark/serialize.js

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/* eslint-disable no-console */
2+
const Ajv = require("ajv/dist/jtd").default
3+
const Benchmark = require('benchmark')
4+
const jtdValidationTests = require("../spec/json-typedef-spec/tests/validation.json")
5+
6+
const ajv = new Ajv
7+
const suite = new Benchmark.Suite
8+
const tests = []
9+
10+
for (const testName in jtdValidationTests) {
11+
const {schema, instance, errors} = jtdValidationTests[testName]
12+
const valid = errors.length === 0
13+
if (!valid) continue
14+
tests.push({
15+
serialize: ajv.compileSerializer(schema),
16+
data: instance
17+
})
18+
}
19+
20+
suite.add("JTD test suite: compiled JTD serializers", () => {
21+
for (const test of tests) {
22+
test.serialize(test.data)
23+
}
24+
})
25+
26+
suite.add("JTD test suite: JSON.stringify", () => {
27+
for (const test of tests) {
28+
JSON.stringify(test.data)
29+
}
30+
})
31+
32+
const testSchema = {
33+
definitions: {
34+
obj: {
35+
properties: {
36+
foo: {type: "string"},
37+
bar: {type: "int8"}
38+
}
39+
}
40+
},
41+
properties: {
42+
a: {ref: "obj"}
43+
},
44+
optionalProperties: {
45+
b: {ref: "obj"}
46+
}
47+
}
48+
49+
const testData = {
50+
a: {
51+
foo: "foo1",
52+
bar: 1
53+
},
54+
b: {
55+
foo: "foo2",
56+
bar: 2
57+
}
58+
}
59+
60+
const serializer = ajv.compileSerializer(testSchema)
61+
62+
suite.add("test data: compiled JTD serializer", () => serializer(testData))
63+
suite.add("test data: JSON.stringify", () => JSON.stringify(testData))
64+
65+
console.log()
66+
67+
suite
68+
.on("cycle", (event) => console.log(String(event.target)))
69+
.on("complete", function () {
70+
// eslint-disable-next-line no-invalid-this
71+
console.log('The fastest is "' + this.filter('fastest').map('name') + '"');
72+
})
73+
.run({async: true})

package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@
2727
"test-all": "npm run test-cov && if-node-version 12 npm run test-browser",
2828
"test": "npm link && npm link ajv && npm run json-tests && npm run eslint && npm run test-cov",
2929
"test-ci": "AJV_FULL_TEST=true npm test",
30-
"prepublish": "npm run build"
30+
"prepublish": "npm run build",
31+
"benchmark": "npm i && npm run build && npm link && cd ./benchmark && npm link ajv && npm i && node ./serialize"
3132
},
3233
"nyc": {
3334
"exclude": [

0 commit comments

Comments
 (0)