Skip to content

Commit 2d6d9c4

Browse files
authored
avoid main encapsulation for simple object (#594)
* avoid main encapsulation for simple object * avoid ternary operation and add a comment
1 parent 3b1d56c commit 2d6d9c4

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

benchmark/bench.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,27 @@ const benchmarks = [
214214
b5: true
215215
}
216216
},
217+
{
218+
name: 'simple object',
219+
schema: {
220+
title: 'Example Schema',
221+
type: 'object',
222+
properties: {
223+
firstName: {
224+
type: 'string'
225+
},
226+
lastName: {
227+
type: ['string', 'null']
228+
},
229+
age: {
230+
description: 'Age in years',
231+
type: 'integer',
232+
minimum: 0
233+
}
234+
}
235+
},
236+
input: { firstName: 'Max', lastName: 'Power', age: 22 }
237+
},
217238
{
218239
name: 'object with const string property',
219240
schema: {

index.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,15 +123,30 @@ function build (schema, options) {
123123
const location = new Location(schema, rootSchemaId)
124124
const code = buildValue(location, 'input')
125125

126-
const contextFunctionCode = `
126+
let contextFunctionCode
127+
128+
// If we have only the invocation of the 'anonymous0' function, we would
129+
// basically just wrap the 'anonymous0' function in the 'main' function and
130+
// and the overhead of the intermediate variabe 'json'. We can avoid the
131+
// wrapping and the unnecessary memory allocation by aliasing 'anonymous0' to
132+
// 'main'
133+
if (code === 'json += anonymous0(input)') {
134+
contextFunctionCode = `
135+
${contextFunctions.join('\n')}
136+
const main = anonymous0
137+
return main
138+
`
139+
} else {
140+
contextFunctionCode = `
127141
function main (input) {
128142
let json = ''
129143
${code}
130144
return json
131145
}
132146
${contextFunctions.join('\n')}
133147
return main
134-
`
148+
`
149+
}
135150

136151
const serializer = new Serializer(options)
137152
const validator = new Validator(options.ajv)

0 commit comments

Comments
 (0)