fastify/fast-json-stringify

bigger function body => perf hit

Uzlopak opened this issue · 3 comments

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

tldr; Is this just some mistake and micro benchmarking issue, or is there a general deoptimzation happening when we concat multiple times a string. Maybe something which is related to flatstr?

Lets say I have the following:

'use strict'

const Benchmark = require('benchmark')
Benchmark.options.minSamples = 100

const suite = Benchmark.Suite()

const FJS = require('.')

const shortStringify = FJS({
  type: 'object',
  properties: {
    n1: { type: 'number' },
    n2: { type: 'number' },
    n3: { type: 'number' },
    n4: { type: 'number' },
    n5: { type: 'number' },
  }
})

const fullStringify = FJS({
  type: 'object',
  properties: {
    n1: { type: 'number' },
    n2: { type: 'number' },
    n3: { type: 'number' },
    n4: { type: 'number' },
    n5: { type: 'number' },
    n6: { type: 'number' },
  }
})

const input = {
  n1: 42,
  n2: 42,
  n3: 42,
  n4: 42,
  n5: 42,
  n6: 42,
}

suite
  .add('short', () => {
    shortStringify(input)
  })
  .add('full', () => {
    fullStringify(input)
  })
  .on('cycle', (event) => {
    console.log(String(event.target))
  })
  .run()

We get the following bench:

 node bench
short x 1,196,654,692 ops/sec ±0.13% (193 runs sampled)
full x 9,419,519 ops/sec ±0.29% (193 runs sampled)

So from basically crazy fast we get to poor performance.

It seems to be directly connected with the concating the strings. Before I merged #596 it the break point was at 4 elements.

@Uzlopak Can you swap the bench order and check the result? If you want to get clear results in the micro benchmarking I would recommend running each bench in diff process/thread.

I guess if the function is not long enough it will just inline and optimize it away. Quite interesting effect. LOL

Indeed ;). it's great.