/
ajv-vs-parameter.mjs
98 lines (89 loc) · 2.16 KB
/
ajv-vs-parameter.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import Benchmark from 'benchmark';
import addFormats from 'ajv-formats';
import Ajv from 'ajv';
import Parameter from 'parameter';
import { Type } from '../typebox';
const getAjvInstance = () =>
addFormats(new Ajv({}), [
'date-time',
'time',
'date',
'email',
'hostname',
'ipv4',
'ipv6',
'uri',
'uri-reference',
'uuid',
'uri-template',
'json-pointer',
'relative-json-pointer',
'regex',
])
.addKeyword('kind')
.addKeyword('modifier');
const suite = new Benchmark.Suite();
const DATA = {
name: 'xiekw2010',
description: 'desc',
location: 'shanghai',
};
const ajv = getAjvInstance();
const p = new Parameter();
const typeboxRule = Type.Object({
name: Type.String(),
description: Type.Optional(Type.String()),
location: Type.Enum({ shanghai: 'shanghai', hangzhou: 'hangzhou' }),
});
const parameterRule = {
name: 'string',
description: {
type: 'string',
required: false,
},
location: ['shanghai', 'hangzhou'],
};
// add tests
suite
.add('#ajv', () => {
const rule = Type.Object({
name: Type.String(),
description: Type.Optional(Type.String()),
location: Type.Enum({ shanghai: 'shanghai', hangzhou: 'hangzhou' }),
});
ajv.validate(rule, DATA);
})
.add('#ajv define once', () => {
ajv.validate(typeboxRule, DATA);
})
.add('#parameter', () => {
const rule = {
name: 'string',
description: {
type: 'string',
required: false,
},
location: ['shanghai', 'hangzhou'],
};
p.validate(rule, DATA);
})
.add('#parameter define once', () => {
p.validate(parameterRule, DATA);
})
// add listeners
.on('cycle', event => {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ async: true });
/*
MacBook Pro(2.2 GHz 六核Intel Core i7)
#ajv x 941 ops/sec ±3.97% (73 runs sampled)
#ajv define once x 17,188,370 ops/sec ±11.53% (73 runs sampled)
#parameter x 2,544,118 ops/sec ±4.68% (79 runs sampled)
#parameter define once x 2,541,590 ops/sec ±5.34% (77 runs sampled)
Fastest is #ajv define once
*/