Repository navigation
perf(traverse): improve generateUid and push - #18413
Conversation
`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
|
Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/62553 |
|
commit: |
There was a problem hiding this comment.
🟢 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
Refactor scope binding tests to use updated declaration retrieval. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
|
This patch brings further performance improvements. :)
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) {
|
|
The patch above no longer initializes |
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. |
|
Oh no, I made a stupid mistake. I forgot to push the changes. |
That's fine, new PR is also great. |

This PR is sprung off from the ongoing big destructuring refactor: In this PR we improve the performance of
Scope#generateUidandScope#push:Scope#generateUidbecomes quadratic when it generated many uids with the same name, for example_excludedwith object rest or_refwith 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'sreferencesSet, which is what rejects every uid already generated.Scope#generateUidreferencesSetis now checked first, since it is the cheapest check.referencesSetand base name, we remember the index of the first candidate that isn't in the set. Names are never removed from areferencesSet(re-crawling the program creates a new one, and the cache is keyed on the Set through aWeakMap), 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#pushdeclarPath.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 waygetwould. 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 comparesmainand this branch, one process per case, median ops/s:generateUid×100generateUid×1000generateDeclaredUidIdentifier×100generateDeclaredUidIdentifier×1000