Skip to content

Commit

Permalink
perf: create faker schema just once (#30)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
EvanHahn authored Dec 2, 2024
1 parent 003d0d0 commit d6d1e69
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
@@ -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<string>}} */
Expand All @@ -13,16 +14,32 @@ export function listSchemas() {
return result
}

/** @type {Map<SchemaName, ReturnType<typeof createFakerSchema>>} 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<Extract<import('@comapeo/schema').MapeoDoc, { schemaName: TSchemaName }>>}
*/
export function generate(schemaName, { count } = {}) {
isValidSchemaName(schemaName)

const targetSchema = docSchemas[schemaName]
const schema = getFakerSchema(schemaName)

const numberToGenerate = count || 1

/** @type {Array<Extract<import('@comapeo/schema').MapeoDoc, { schemaName: TSchemaName }>>} */
Expand All @@ -31,7 +48,7 @@ export function generate(schemaName, { count } = {}) {
for (let i = 0; i < numberToGenerate; i++) {
result.push(
/** @type {Extract<import('@comapeo/schema').MapeoDoc, { schemaName: TSchemaName }>} */ (
JSONSchemaFaker.generate(createFakerSchema(targetSchema))
JSONSchemaFaker.generate(schema)
),
)
}
Expand Down

0 comments on commit d6d1e69

Please sign in to comment.