From d6d1e696bf50b313a47f8e90439fc2ffd7a36e6a Mon Sep 17 00:00:00 2001 From: Evan Hahn Date: Mon, 2 Dec 2024 14:09:39 -0600 Subject: [PATCH] perf: create faker schema just once (#30) This change creates the faker schema just once and reuses it, rather than unnecessarily creating it for each generated document. On my machine, this speeds up `node --test` by about 350 milliseconds, or about 8%. I suspect the gains will be a little bigger in `@comapeo/core` where we call `generate` a lot more. --- index.js | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index fc1f6b9..2e0867a 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,7 @@ import { docSchemas } from '@comapeo/schema' import { JSONSchemaFaker, createFakerSchema } from './lib/faker.js' import { extractSchemaVersion, isValidSchemaName } from './lib/schema.js' +/** @typedef {import('@comapeo/schema/dist/types.js').SchemaName} SchemaName */ export function listSchemas() { /** @type {{[name: string]: Array}} */ @@ -13,8 +14,23 @@ export function listSchemas() { return result } +/** @type {Map>} schemaCache */ +const fakerSchemaCache = new Map() + /** - * @template {import('@comapeo/schema/dist/types.js').SchemaName} TSchemaName + * @param {SchemaName} schemaName + */ +function getFakerSchema(schemaName) { + const cached = fakerSchemaCache.get(schemaName) + if (cached) return cached + const targetSchema = docSchemas[schemaName] + const result = createFakerSchema(targetSchema) + fakerSchemaCache.set(schemaName, result) + return result +} + +/** + * @template {SchemaName} TSchemaName * @param {TSchemaName} schemaName * @param {{version?: string, count?: number}} [options] * @returns {Array>} @@ -22,7 +38,8 @@ export function listSchemas() { export function generate(schemaName, { count } = {}) { isValidSchemaName(schemaName) - const targetSchema = docSchemas[schemaName] + const schema = getFakerSchema(schemaName) + const numberToGenerate = count || 1 /** @type {Array>} */ @@ -31,7 +48,7 @@ export function generate(schemaName, { count } = {}) { for (let i = 0; i < numberToGenerate; i++) { result.push( /** @type {Extract} */ ( - JSONSchemaFaker.generate(createFakerSchema(targetSchema)) + JSONSchemaFaker.generate(schema) ), ) }