Skip to content

Conversation

@cesco69
Copy link
Contributor

@cesco69 cesco69 commented Jan 14, 2026

Just a small performance improvements when an object contains only one key or an array only one item, the fjs code avoid to check to addComma

Currently this schema

fjs({
    title: 'additionalProperties',
    type: 'object',
    properties: {
      foo: {
        type: 'string'
      }
    },
    additionalProperties: false
})

produce this fjs code

function anonymous0 (input) {
      const obj = (input && typeof input.toJSON === 'function')
    ? input.toJSON()
    : input

      if (obj === null) return JSON_STR_EMPTY_OBJECT

      let json = JSON_STR_BEGIN_OBJECT
let addComma = false

      const value_foo_0 = obj["foo"]
      if (value_foo_0 !== undefined) {
        !addComma && (addComma = true) || (json += JSON_STR_COMMA)
        json += "\"foo\":"

        if (typeof value_foo_0 !== 'string') {
          if (value_foo_0 === null) {
            json += JSON_STR_EMPTY_STRING
          } else if (value_foo_0 instanceof Date) {
            json += JSON_STR_QUOTE + value_foo_0.toISOString() + JSON_STR_QUOTE
          } else if (value_foo_0 instanceof RegExp) {
            json += asString(value_foo_0.source)
          } else {
            json += asString(value_foo_0.toString())
          }
        } else {
          json += asString(value_foo_0)
        }

      }

    return json + JSON_STR_END_OBJECT

    }

whith this PR

function anonymous0 (input) {
      const obj = (input && typeof input.toJSON === 'function')
    ? input.toJSON()
    : input

      if (obj === null) return JSON_STR_EMPTY_OBJECT

      let json = JSON_STR_BEGIN_OBJECT

      const value_foo_0 = obj["foo"]
      if (value_foo_0 !== undefined) {

        json += "\"foo\":"

        if (typeof value_foo_0 !== 'string') {
          if (value_foo_0 === null) {
            json += JSON_STR_EMPTY_STRING
          } else if (value_foo_0 instanceof Date) {
            json += JSON_STR_QUOTE + value_foo_0.toISOString() + JSON_STR_QUOTE
          } else if (value_foo_0 instanceof RegExp) {
            json += asString(value_foo_0.source)
          } else {
            json += asString(value_foo_0.toString())
          }
        } else {
          json += asString(value_foo_0)
        }

      }

    return json + JSON_STR_END_OBJECT

    }

Diff
image

Side note: the benchmark don't cover this case

@cesco69 cesco69 marked this pull request as ready for review January 14, 2026 09:59
Copy link
Member

@mcollina mcollina left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@mcollina mcollina merged commit bb20492 into fastify:main Jan 14, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants