Performance comparison of joi and ajv libraries

Execution of tests to compare the performance between the joi library and the ajv library

Introduction

This document details the execution of the tests to compare the performance between the joi library, currently used in aura-bot development, and the ajv library, which stands out for its performance orientation.

The tests performed are based on a simple channel object. This property is defined in the channelData object to communicate with the bot.

Test code

const Ajv = require('ajv');
const Benchmark = require('benchmark');
const Joi = require('joi');

const channelSchema = {
  type: 'object',
  additionalProperties: false,
  properties: {
    id: {
      type: 'string',
      format: 'uuid'
    },
    interfaceLanguage: {
      type: 'string'
    },
    modality: {
      type: 'string',
      'enum': [
        'audio',
        'text',
        'form'
      ]
    }
  },
  required: [
    'id',
    'modality'
  ]
};

const ajvValidate = new Ajv().compile(channelSchema);

const joiSchema = Joi.object({
  id: Joi.string().guid().required(),
  interfaceLanguage: Joi.string(),
  modality: Joi.string()
    .valid('audio', 'text', 'form')
    .required()
}).unknown(false);

const suite = new Benchmark.Suite();
const value = { id: '45494a5b-835a-4fff-a813-b3d2be529dbe', interfaceLanguage: 'es-ES', modality: 'text' };

suite.add('Joi', () => {
  joiSchema.validate(value);
}).add('Ajv', () => {
  ajvValidate(value);
});

suite.on('cycle', (event) => {
  console.log(event.target.toString());
});

suite.on('complete', function () {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
});

suite.run({ async: true });

Test result

$ node src/index.js
Joi x 284,136 ops/sec ±25.59% (61 runs sampled)
Ajv x 5,087,995 ops/sec ±1.57% (74 runs sampled)
Fastest is Ajv