Skip to content

Commit 0f0cf51

Browse files
mcollinadelvedor
authored andcommitted
speed up creation time by 100x. (#93)
We cache a module-wide Ajv instance instead of creating a new one to validate each schema and then throw it away.
1 parent ddbc147 commit 0f0cf51

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

bench.js

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,13 @@ const obj = {
3535

3636
const multiArray = []
3737

38-
const stringify = require('.')(schema)
39-
const stringifyUgly = require('.')(schema, { uglify: true })
40-
const stringifyArray = require('.')(arraySchema)
41-
const stringifyArrayUgly = require('.')(arraySchema, { uglify: true })
42-
const stringifyString = require('.')({ type: 'string' })
43-
const stringifyStringUgly = require('.')({ type: 'string', uglify: true })
38+
const FJS = require('.')
39+
const stringify = FJS(schema)
40+
const stringifyUgly = FJS(schema, { uglify: true })
41+
const stringifyArray = FJS(arraySchema)
42+
const stringifyArrayUgly = FJS(arraySchema, { uglify: true })
43+
const stringifyString = FJS({ type: 'string' })
44+
const stringifyStringUgly = FJS({ type: 'string', uglify: true })
4445
var str = ''
4546

4647
for (var i = 0; i < 10000; i++) {
@@ -56,6 +57,10 @@ for (i = 0; i < 1000; i++) {
5657
multiArray.push(obj)
5758
}
5859

60+
suite.add('FJS creation', function () {
61+
FJS(schema)
62+
})
63+
5964
suite.add('JSON.stringify array', function () {
6065
JSON.stringify(multiArray)
6166
})

index.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
var Ajv = require('ajv')
44
var merge = require('deepmerge')
55

6+
// This Ajv instance is used to validate that the passed schema
7+
// is valid json schema. We reuse the instance to avoid having to
8+
// pay the ajv creation cost more than once.
9+
var ajv = new Ajv()
10+
611
var uglify = null
712
var isLong
813
try {
@@ -791,13 +796,17 @@ function loadUglify () {
791796
}
792797

793798
function isValidSchema (schema, externalSchema) {
794-
const ajv = new Ajv()
795799
if (externalSchema) {
796800
Object.keys(externalSchema).forEach(key => {
797801
ajv.addSchema(externalSchema[key], key)
798802
})
799803
}
800804
ajv.compile(schema)
805+
if (externalSchema) {
806+
Object.keys(externalSchema).forEach(key => {
807+
ajv.removeSchema(key)
808+
})
809+
}
801810
}
802811

803812
module.exports = build

0 commit comments

Comments
 (0)