Skip to content

fix: faster parse() for plain versions and fewer passes in Range - #959

Open
TobiasPol wants to merge 3 commits into
npm:mainfrom
TobiasPol:fix/faster-parse-and-ranges
Open

TobiasPol wants to merge 3 commits into
npm:mainfrom
TobiasPol:fix/faster-parse-and-ranges

Conversation

@TobiasPol

Copy link
Copy Markdown

Three independent commits. Each passes npm test (100% coverage) and npm run lint on its own, so any of them can be reviewed, reordered or dropped separately. No API or behaviour change, and the LRU cache is untouched (see #893).

  1. fix: parse plain X.Y.Z versions without the regular expression
    • Most versions npm sees are plain X.Y.Z. They are now read in one backward pass: digits and two dots, no leading zeros, at most 9 digits per part.
    • Anything else is rejected within a character or two and goes to the existing regex, so results cannot differ.
    • Two small changes in the same function:
      • the prerelease /^[0-9]+$/ test becomes a char-code loop;
      • String#match becomes RegExp#exec.
  2. fix: skip whitespace and regex passes that cannot change a range
    • Range and Comparator ran every normalization step on every input. A shared, conservative pre-check (every character \s matches is <= 0x20 or >= 0xa0) now skips trim/split/replace passes that cannot change the string.
    • || is only split when it is present.
    • A range with a single comparator is built directly.
  3. fix: compare directly in Comparator.test for parsed operators
    • For the five operators the parser produces, test() calls SemVer#compare directly instead of going through cmp().
    • Any other operator (a hand-set '!=', or an invalid one) still goes through cmp() and behaves and throws as before.

Benchmarks

  • Setup: Node 26.13.1, macOS on Apple Silicon (8 cores), main = b37b033.
  • Caveat: the machine was not idle (load average 5 to 9 from desktop apps), so I ran the upstream scripts twice with the tree order swapped and report both runs.

benchmarks/bench-parse.js (ops/sec, this branch / main)

Cases Run 1 Run 2
parse(1.0.0), parse(2.1.0), parse(3.2.1) 2.68 to 2.73x 2.64 to 2.77x
parse(v1.2.3) 0.87x 1.02x
other 18 valid cases (prerelease, build) 0.94 to 1.06x 0.90 to 1.07x
9 invalid cases 0.95 to 0.99x 0.95 to 1.00x
  • Single cases move by up to ±10% between full runs on this machine.
  • In focused runs (only these cases, fresh process), parse(v1.2.3) is 1.00 to 1.04x, parse(xyz) 0.97 to 1.00x, and parse(1.2.3-123) 1.07 to 1.11x.
  • Invalid inputs pay a few percent for the extra check before the regex.

benchmarks/bench-satisfies.js: 1.42 to 1.62x across all 12 cases (one run).

A real dependency tree. #893 asked how changes like this behave on a real install, so I measured that too:

  • Corpus: every dependency edge in this repository's own installed dev tree (npm install here: 916 packages, 1,675 edges, 395 distinct ranges).
  • Workload: each edge checked once as satisfies(installedVersion, declaredRange), which is roughly what validating a tree does.
  • Method: 15 fresh processes per tree, alternating trees. All 1,675 results are identical.
main this branch
first pass (what one install pays) 10.0 ms 7.4 ms 1.35x
later passes (median of 40) 1.11 ms 0.54 ms 2.04x
Scripts for the real-tree numbers

node corpus.mjs edges.json . builds the edge list from ./node_modules; node bench-real.mjs edges.json 15 <path-to-main> <path-to-branch> runs the comparison.

// corpus.mjs
// Builds a list of real dependency edges (installed version, declared range) from node_modules trees.
import { readdirSync, readFileSync, existsSync, writeFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
const roots = process.argv.slice(3);
const out = process.argv[2];
const pkgs = [];
function walk(nm) {
  if (!existsSync(nm)) return;
  for (const e of readdirSync(nm)) {
    if (e.startsWith('.')) continue;
    if (e.startsWith('@')) { for (const s of readdirSync(join(nm, e))) visit(join(nm, e, s)); } else visit(join(nm, e));
  }
}
function visit(dir) {
  const pj = join(dir, 'package.json');
  if (!existsSync(pj)) return;
  pkgs.push(dir);
  walk(join(dir, 'node_modules'));
}
function resolveVersion(fromDir, name) {
  let d = fromDir;
  while (true) {
    const pj = join(d, 'node_modules', name, 'package.json');
    if (existsSync(pj)) { try { return JSON.parse(readFileSync(pj, 'utf8')).version; } catch { return null; } }
    const up = dirname(d);
    if (up === d) return null;
    d = up;
  }
}
for (const r of roots) { pkgs.push(r); walk(join(r, 'node_modules')); }
const edges = [];
const bad = /^(npm:|git|file:|link:|workspace:|http|github:|catalog:)|\//;
for (const dir of pkgs) {
  let p; try { p = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); } catch { continue; }
  const deps = { ...(p.dependencies || {}), ...(p.optionalDependencies || {}), ...(p.peerDependencies || {}) };
  for (const [name, range] of Object.entries(deps)) {
    if (typeof range !== 'string' || bad.test(range)) continue;
    const v = resolveVersion(dir, name);
    if (v) edges.push([v, range]);
  }
}
writeFileSync(out, JSON.stringify(edges));
const ranges = new Set(edges.map((e) => e[1]));
const versions = new Set(edges.map((e) => e[0]));
console.log(`packages ${pkgs.length}, edges ${edges.length}, distinct ranges ${ranges.size}, distinct versions ${versions.size}, prerelease versions ${[...versions].filter((v) => v.includes('-')).length}`);
// bench-real.mjs
// Real-tree satisfies() benchmark: every dependency edge of an installed node_modules tree, checked the
// way npm validates a tree. One fresh process per sample; trees alternate. Reports the first (cold)
// pass, which is what a single install pays, and the median of later (warm) passes.
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const [mode, ...rest] = process.argv.slice(2);
if (mode === '--child') {
  const [tree, edgesFile] = rest;
  const satisfies = createRequire(import.meta.url)(`${tree}/functions/satisfies`);
  const edges = JSON.parse(readFileSync(edgesFile, 'utf8'));
  const pass = () => { let n = 0; for (const [v, r] of edges) if (satisfies(v, r)) n++; return n; };
  const t0 = process.hrtime.bigint(); const ok = pass(); const cold = Number(process.hrtime.bigint() - t0) / 1e3;
  const warm = [];
  for (let i = 0; i < 40; i++) { const s = process.hrtime.bigint(); pass(); warm.push(Number(process.hrtime.bigint() - s) / 1e3); }
  warm.sort((a, b) => a - b);
  console.log(JSON.stringify({ cold, warm: warm[20], ok }));
  process.exit(0);
}
const [edgesFile, samplesArg, ...trees] = [mode, ...rest];
const samples = Number(samplesArg);
const res = Object.fromEntries(trees.map((t) => [t, { cold: [], warm: [], ok: null }]));
const self = fileURLToPath(import.meta.url);
for (let s = 0; s < samples; s++) {
  const order = s % 2 ? [...trees].reverse() : trees;
  for (const t of order) {
    const r = JSON.parse(spawnSync(process.execPath, [self, '--child', t, edgesFile], { encoding: 'utf8' }).stdout);
    res[t].cold.push(r.cold); res[t].warm.push(r.warm);
    if (res[t].ok === null) res[t].ok = r.ok; else if (res[t].ok !== r.ok) throw new Error('result mismatch');
  }
}
const med = (xs) => { const a = [...xs].sort((x, y) => x - y); return a[a.length >> 1]; };
const base = trees[0];
const oks = new Set(trees.map((t) => res[t].ok));
if (oks.size !== 1) throw new Error('trees disagree on satisfied edge count');
console.log(`edges satisfied: ${res[base].ok} (identical in every tree)`);
for (const t of trees) {
  const c = med(res[t].cold), w = med(res[t].warm);
  console.log(`${t.split('/').pop().padEnd(18)} cold pass ${c.toFixed(0).padStart(6)} us (${(med(res[base].cold) / c).toFixed(2)}x)   warm pass ${w.toFixed(0).padStart(6)} us (${(med(res[base].warm) / w).toFixed(2)}x)`);
}

Correctness

  • Tests and lint: npm test passes 55 suites with 23,502 assertions at 100% coverage; npm run lint is clean.
  • Differential check against unmodified main:
    • 38,239 assertions comparing results and thrown error messages.
    • APIs: parse, valid, compare, new Range().range, satisfies and Comparator#test.
    • Options: all four combinations of loose and includePrerelease.
    • Inputs: seeded random versions and ranges, plus edge cases (prerelease, build, v prefix, unicode whitespace, invalid input, the 9/10-digit boundary and MAX_SAFE_INTEGER).
    • I'm happy to share the script.
  • Details worth a look:
    • The fast path accepts at most 9 digits per part, so it never needs the MAX_SAFE_INTEGER check; longer numbers take the regex path as before (tested at 9, 10 and 16 digits).
    • hasMaybeWhitespace is deliberately conservative. A test checks that every character in WHITESPACE_CHARACTERS is caught.

How this was made

I built this with AI coding agents. They worked inside a harness that only accepts a change when the test suite stays green and the change matches unmodified main on the differential check above. I then reviewed every line myself. I'm happy to split this, drop a commit, or rework anything.

Most versions seen by npm are plain `X.Y.Z`. They are now read in one pass
from the end of the string (digits and two dots, no leading zeros, up to 9
digits per part); anything else is rejected after a character or two and
goes to the regular expression as before, so results never differ. Also
replaces the per-identifier `/^[0-9]+$/` test in the prerelease map with a
char-code loop and `String#match` with `RegExp#exec`.
Range and Comparator ran every normalization step on every input, even
when the string had no whitespace, no `+`, `^`, `~` or `*`. A shared,
conservative pre-check (every character `\s` matches is <= 0x20 or
>= 0xa0) now skips the trim/split/replace passes that cannot change the
string, `||` is only split when present, and a range with a single
comparator is built directly. Inputs that might contain whitespace still
go through the exact normalization, so results are unchanged.
Comparator.test went through cmp(), which re-wraps both sides in SemVer
and dispatches on the operator string. For the five operators the parser
produces ('', '>', '>=', '<', '<=') it now calls SemVer#compare directly;
any other operator still goes through cmp(), so a hand-set '!=' or an
invalid operator behaves (and throws) exactly as before.
@TobiasPol
TobiasPol requested a review from a team as a code owner November 27, 2026 12:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant