Skip to content

bundle() time grows quadratically with the number of $refs #442

Done

Description

@icguner

bundle() gets disproportionately slow on schemas with many $refs. Every $ref triggers a linear scan of the whole inventory array, so N refs cost about N^2/2 comparisons. dereference() on the same input stays linear.

Reproduction

import $RefParser from '@apidevtools/json-schema-ref-parser';

// n definitions and n internal $refs, each pointing at a different definition.
function makeSchema(n) {
  const defs = {};
  for (let i = 0; i < n; i++) defs['d' + i] = { type: 'string' };
  return { items: Array.from({ length: n }, (_, i) => ({ $ref: '#/defs/d' + i })), defs };
}

for (const n of [8000, 16000, 32000]) {
  const times = {};
  for (const method of ['bundle', 'dereference']) {
    const schema = makeSchema(n);
    const start = performance.now();
    await $RefParser[method](schema);
    times[method] = Math.round(performance.now() - start);
  }
  console.log(`${n} $refs: bundle ${times.bundle} ms, dereference ${times.dereference} ms`);
}

Output:

8000 $refs: bundle 518 ms, dereference 159 ms
16000 $refs: bundle 1493 ms, dereference 357 ms
32000 $refs: bundle 5216 ms, dereference 760 ms
$refs bundle() dereference()
8000 518 ms 159 ms
16000 1493 ms 357 ms
32000 5216 ms 760 ms

Each doubling makes bundle() about 3-3.5x slower, while dereference() roughly doubles. A CPU profile of a 30000-ref run shows 59% of the samples in findInInventory.

Tested with v16.0.8 (main at 735a407) on Node v26.13.0, Windows 11; single run. 14.0.1 shows the same growth.

Cause

function findInInventory(inventory: InventoryEntry[], $refParent: any, $refKey: any) {
for (const existingEntry of inventory) {
if (existingEntry && existingEntry.parent === $refParent && existingEntry.key === $refKey) {
return existingEntry;
}
}
return undefined;
}

inventory$Ref calls findInInventory(inventory, $refParent, $refKey) for every $ref it visits (L301), and that function walks the flat inventory array from the start looking for an entry with the same parent and key.

Suggested fix

Keep an index next to the array, Map<parent, Map<key, InventoryEntry>>, filled where entries are pushed and cleared in removeFromInventory, and have findInInventory read from it. With that in a local build the three bundle() times above become 225 / 376 / 836 ms, and the output for a small test schema is unchanged. I can open a PR with the change.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions