Skip to content

perf(traverse): improve generateUid and push - #18413

Merged
JLHwung merged 4 commits into
babel:mainfrom
JLHwung:perf-traverse-generate-uid-and-push
Oct 26, 2026
Merged

JLHwung merged 4 commits into
babel:mainfrom
JLHwung:perf-traverse-generate-uid-and-push

Conversation

@JLHwung

@JLHwung JLHwung commented Oct 24, 2026

Copy link
Copy Markdown
Contributor
Q                       A
Fixed Issues?
Patch: Bug Fix?
Major: Breaking Change?
Minor: New Feature?
Tests Added + Pass? Yes
Documentation PR Link
Any Dependency Changes?
Need backport? No
License MIT

This PR is sprung off from the ongoing big destructuring refactor: In this PR we improve the performance of Scope#generateUid and Scope#push:

Scope#generateUid becomes quadratic when it generated many uids with the same name, for example _excluded with object rest or _ref with destructuring. For each candidate (_ref, _ref2, _ref3, …) it checked labels and walked the scope chain twice (hasBinding, hasGlobal), and only then looked in the program's referencesSet, which is what rejects every uid already generated.

Scope#generateUid

  • referencesSet is now checked first, since it is the cheapest check.
  • For each referencesSet and base name, we remember the index of the first candidate that isn't in the set. Names are never removed from a referencesSet (re-crawling the program creates a new one, and the cache is keyed on the Set through a WeakMap), so the candidates before that index don't need to be checked again. Candidates rejected only by a label, binding or global are not cached.

Scope#push

  • It used to call declarPath.get("declarations"), which creates paths for every declarator in the shared hoisted declaration, just to register the binding of the last one. It now creates only the new declarator's path, the same way get would. One side effect goes away: the old code also reset the traversal flags (shouldSkip/shouldStop) and the traversal context of all the sibling declarator paths.

Benchmark

New benchmark benchmark/babel-traverse/generate-uid/bench.mjs (node:bench, Node.js ≥ 26). The table compares main and this branch, one process per case, median ops/s:

Case main this PR Speedup
generateUid ×100 56.5k 695k ~12×
generateUid ×1000 6.0k 818k ~136×
generateDeclaredUidIdentifier ×100 82.7k 239k ~2.9×
generateDeclaredUidIdentifier ×1000 12.7k 289k ~23×

`generateUid` tried every candidate (`_ref`, `_ref2`, `_ref3`...) from
the first one, checking labels and walking the scope chain twice for each
of them before checking the program references, which rejects all the
uids generated so far. Generating many uids with the same name was
quadratic: e.g. `_excluded` with object rest, or `_ref` with
destructuring.

- Check the program references first, as the other checks are slower
- Remember, for each name, the first candidate that isn't referenced:
  names are never removed from the program references (crawling the
  program creates a new set), so the previous candidates don't need to be
  checked again

`push` created the paths of all the declarators of the declaration it
adds to, to register the binding of the last one; it now only creates
that path.

No change in the generated names.

Assisted-by: Claude Opus 5.5
@JLHwung JLHwung added pkg: traverse (scope) PR: Performance 🏃‍♀️ A type of pull request used for our changelog categories labels Oct 24, 2026
@babel-bot

babel-bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/62553

@pkg-pr-new

pkg-pr-new Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

commit: 0ef2773

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No blocking correctness issues remain; feedback is limited to a minor test assertion improvement.

1 open issue
What changed in this PR

This PR improves Babel traversal performance when repeatedly generating unique identifiers and inserting hoisted declarations.

Changes:

  • Cache UID candidate positions and check references before scope-chain lookups.
  • Create only the newly inserted declarator’s path in Scope#push.
  • Add regression tests and a baseline-versus-current performance benchmark.
File Description
packages/​babel-traverse/​test/​scope.js Tests UID sequencing, cache reset, label collisions, and declarator bindings.
packages/​babel-traverse/​src/​scope/​index.ts Optimizes UID generation and declarator-path creation.
benchmark/​babel-traverse/​generate-uid/​bench.mjs Benchmarks repeated UID generation and declaration insertion.

Review effort: Balanced

Comment thread packages/babel-traverse/test/scope.js Resolved
Refactor scope binding tests to use updated declaration retrieval.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
@liuxingbaoyu

liuxingbaoyu commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

This patch brings further performance improvements. :)
It includes a behavioral change, though I consider it more of a bug fix:
Previously, global variables added via addGlobal were not registered on the program scope, whereas those collected automatically were. Now, this behavior has been unified.

Scenario UIDs per Batch Original PR (ns/op) Current (ns/op) Speedup
No collisions 100 787 372 2.12×
No collisions 1,000 809 359 2.25×
No collisions 10,000 858 404 2.12×
Global collision 100 2,974 359 8.29×
Global collision 1,000 25,096 366 68.57×
Label collision 100 2,771 2,215 1.25×
Label collision 1,000 25,070 24,024 1.04×
diff --git a/packages/babel-traverse/src/scope/index.ts b/packages/babel-traverse/src/scope/index.ts
index ccbf0b26d1..eae502f88b 100644
--- a/packages/babel-traverse/src/scope/index.ts
+++ b/packages/babel-traverse/src/scope/index.ts
@@ -224,14 +224,6 @@ function gatherNodeParts(node: t.Node | null | undefined, parts: NodePart[]) {
   }
 }

-/**
- * For each `referencesSet` of a program scope, and each uid base name, the
- * index of the first candidate (see `generateUid`) that is not in it. Names
- * are never removed from a `referencesSet` (crawling the program creates a
- * new one), so the candidates before it don't need to be checked again.
- */
-const uidCandidateStart = new WeakMap<Set<string>, Map<string, number>>();
-
 function uidCandidate(name: string, i: number) {
   // Ideally we would just use (i - 1) as the suffix, but that generates
   // unnecessary changes in every single file generated by Babel :)
@@ -248,10 +240,11 @@ function resetScope(scope: Scope) {
   if (scope.path.type === "Program") {
     scope.referencesSet = new Set();
     scope.uidsSet = new Set();
+    scope.globals = Object.create(null);
+    scope.uidCandidateStart = undefined;
   }

   scope.bindings = Object.create(null);
-  scope.globals = Object.create(null);
 }

 function isAnonymousFunctionExpression(
@@ -443,9 +436,16 @@ class Scope {
   bindings!: Record<string, Binding>;
   /** Only defined in the program scope */
   referencesSet?: Set<string>;
-  globals!: Record<string, t.Identifier | t.JSXIdentifier>;
+  /** Only defined in the program scope */
+  globals?: Record<string, t.Identifier | t.JSXIdentifier>;
   /** Only defined in the program scope */
   uidsSet?: Set<string>;
+  /**
+   * Only defined in the program scope. For each uid base name, the index of
+   * the first candidate not in `referencesSet` or `globals`. These names stay
+   * reserved until the program is crawled, when the cache is also reset.
+   */
+  uidCandidateStart?: Map<string, number>;
   data!: Record<string | symbol, unknown>;
   crawling!: boolean;

@@ -532,34 +532,33 @@ class Scope {
    * Generate a unique `_id1` binding.
    */

-  generateUid(name: string = "temp"): string {
+  generateUid(name?: string): string {
+    name = name
+      ? toIdentifier(name).replace(/^_+/, "").replace(/\d+$/g, "")
+      : "temp";
-    name = toIdentifier(name).replace(/^_+/, "").replace(/\d+$/g, "");

     const program = this.getProgramParent();
-    const { referencesSet } = program;
+    const { referencesSet, globals } = program;

-    let starts = uidCandidateStart.get(referencesSet);
-    if (!starts) uidCandidateStart.set(referencesSet, (starts = new Map()));
-    // Skip the candidates that are referenced, which they will stay
+    const starts = (program.uidCandidateStart ??= new Map());
     let i = starts.get(name) ?? 0;
-    while (referencesSet.has(uidCandidate(name, i))) i++;
-    starts.set(name, i);
+    let firstUnreferenced: number | undefined;

-    let uid;
-    do {
-      uid = uidCandidate(name, i++);
-    } while (
-      // The cheapest check first, as the others walk the scope chain
-      referencesSet.has(uid) ||
-      this.hasLabel(uid) ||
-      this.hasBinding(uid) ||
-      this.hasGlobal(uid)
-    );
+    for (; ; i++) {
+      const uid = uidCandidate(name, i);
+      if (referencesSet.has(uid) || globals[uid]) continue;

-    referencesSet.add(uid);
-    program.uidsSet.add(uid);
+      firstUnreferenced ??= i;
+
+      if (this.hasLabel(uid)) {
+        continue;
+      }

-    return uid;
+      starts.set(name, firstUnreferenced);
+      referencesSet.add(uid);
+      program.uidsSet.add(uid);
+      return uid;
+    }
   }

   generateUidBasedOnNode(
@@ -806,7 +805,7 @@ class Scope {
   }

   addGlobal(node: t.Identifier | t.JSXIdentifier) {
-    this.globals[node.name] = node;
+    this.getProgramParent().globals[node.name] = node;
   }

   hasUid(name: string): boolean {
@@ -814,13 +813,7 @@ class Scope {
   }

   hasGlobal(name: string): boolean {
-    let scope: Scope | undefined = this;
-
-    do {
-      if (scope.globals[name]) return true;
-    } while ((scope = scope.parent));
-
-    return false;
+    return !!this.getProgramParent().globals[name];
   }

   hasReference(name: string): boolean {
@@ -1126,6 +1119,7 @@ class Scope {
   getProgramParent(): Scope & {
     referencesSet: Set<string>;
     uidsSet: Set<string>;
+    globals: Record<string, t.Identifier | t.JSXIdentifier>;
   } {
     let scope: Scope | undefined = this;
     do {
@@ -1133,6 +1127,7 @@ class Scope {
         return scope as Scope & {
           referencesSet: Set<string>;
           uidsSet: Set<string>;
+          globals: Record<string, t.Identifier | t.JSXIdentifier>;
         };
       }
     } while ((scope = scope.parent));
@@ -1321,6 +1316,7 @@ class Scope {
       info.scope.removeOwnBinding(name);
       info.scope = scope;
       scope.bindings[name] = info;
+      scope.getProgramParent().referencesSet.add(name);
     }
   }

diff --git a/packages/babel-traverse/src/scope/lib/renamer.ts b/packages/babel-traverse/src/scope/lib/renamer.ts
index 80883e5e1c..8c319ec7ff 100644
--- a/packages/babel-traverse/src/scope/lib/renamer.ts
+++ b/packages/babel-traverse/src/scope/lib/renamer.ts
@@ -183,6 +183,7 @@ export default class Renamer {

     scope.removeOwnBinding(oldName);
     scope.bindings[newName] = binding;
+    scope.getProgramParent().referencesSet.add(newName);
     this.binding.identifier.name = newName;

     if (parentDeclar) {

@liuxingbaoyu

Copy link
Copy Markdown
Member

The patch above no longer initializes globals for every scope. I believe this should also improve scope-collection performance, though I’m not entirely sure if it might break code for a very small number of users.

@JLHwung

JLHwung commented Oct 25, 2026

Copy link
Copy Markdown
Contributor Author

The patch above no longer initializes globals for every scope. I believe this should also improve scope-collection performance, though I’m not entirely sure if it might break code for a very small number of users.

Thank you for the patch. The changeset looks good to me, feel free to push to this branch directly so this PR can have correct author credit.

@liuxingbaoyu liuxingbaoyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@JLHwung
JLHwung merged commit 59c7c38 into babel:main Oct 26, 2026
56 checks passed
@JLHwung
JLHwung deleted the perf-traverse-generate-uid-and-push branch October 26, 2026 00:31
@liuxingbaoyu

Copy link
Copy Markdown
Member

Oh no, I made a stupid mistake. I forgot to push the changes.
I’m going to open a new PR. 🤦‍♂️

@JLHwung

JLHwung commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Oh no, I made a stupid mistake. I forgot to push the changes. I’m going to open a new PR. 🤦‍♂️

That's fine, new PR is also great.

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

Labels

pkg: traverse (scope) PR: Performance 🏃‍♀️ A type of pull request used for our changelog categories

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants