8000 perf(transformer): faster UID generation by overlookmotel · Pull Request #10759 · oxc-project/oxc · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
8000

perf(transformer): faster UID generation #10759

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 2, 2025

Conversation

overlookmotel
Copy link
Contributor
@overlookmotel overlookmotel commented May 1, 2025

Alter the algorithm for generating UIDs, to improve its performance.

Previously we stored all existing symbol names which start with _ in an FxHashSet. When creating a UID based on foo, it would first see if _foo is available, then try _foo2, then _foo3, then _foo4 etc.

When creating a lot of UIDs from the same base name (foo in example above), this has poor performance as each attempt requires a separate hashset lookup.

Instead, use an FxHashMap mapping base name to:

  1. Largest number of underscores at start.
  2. Largest numeric prefix on end.

i.e. if there are existing symbols _foo, _bar3, _bar8, _qux, ___qux2, this produces a map:

{
    "foo": { postfix: 1, underscore_count: 1 },
    "bar": { postfix: 8, underscore_count: 1 },
    "qux": { postfix: 2, underscore_count: 3 },
}

When generating a UID, postfix is incremented and UID is constructed as <underscores><base><postfix>.

This requires a maximum of 1 x hashmap lookup and 1 x hashmap insert for each UID. It also reduces the size of the hashmap where many UIDs are created for same base name.

This new algorithm produces almost same UIDs as Babel, but not quite. 3 tests require their outputs to be changed due to UIDs being different.

@github-actions github-actions bot added the C-performance Category - Solution not expected to change functional behavior, only performance label May 1, 2025
Copy link
Contributor Author
overlookmotel commented May 1, 2025

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • 0-merge - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

Copy link
codspeed-hq bot commented May 1, 2025

CodSpeed Instrumentation Performance Report

Merging #10759 will improve performances by 22.4%

Comparing 05-01-perf_transformer_faster_uid_generation (79e462d) with main (dec3c80)

Summary

⚡ 2 improvements
✅ 34 untouched benchmarks

Benchmarks breakdown

Benchmark BASE HEAD Change
transformer[antd.js] 46.7 ms 40.9 ms +14.25%
transformer[cal.com.tsx] 30.9 ms 25.2 ms +22.4%

@overlookmotel overlookmotel force-pushe 8000 d the 05-01-perf_transformer_faster_uid_generation branch from 9fed3f0 to feeb333 Compare May 1, 2025 17:39
@github-actions github-actions bot added the A-transformer Area - Transformer / Transpiler label May 1, 2025
@overlookmotel overlookmotel force-pushed the 05-01-perf_transformer_faster_uid_generation branch from feeb333 to 2f82282 Compare May 1, 2025 23:24
@overlookmotel overlookmotel marked this pull request as ready for review May 1, 2025 23:41
@overlookmotel overlookmotel changed the base branch from 05-01-perf_traverse_get_unique_name_use_string_set_len_ to graphite-base/10759 May 2, 2025 00:07
@overlookmotel overlookmotel force-pushed the graphite-base/10759 branch from 2123607 to c753f75 Compare May 2, 2025 00:07
@overlookmotel overlookmotel force-pushed the 05-01-perf_transformer_faster_uid_generation branch from f743e1b to 6dbb1b0 Compare May 2, 2025 00:07
@overlookmotel overlookmotel changed the base branch from graphite-base/10759 to main May 2, 2025 00:07
Copy link
coderabbitai bot commented May 2, 2025

"""

Walkthrough

This set of changes refactors the unique identifier (UID) name generation logic within the JavaScript AST traversal and transformation infrastructure. The previous approach, which manually tracked used names and generated unique names inline by maintaining a hash set of existing names and unresolved references starting with underscores, is replaced by a new UidGenerator struct encapsulated in its own module. The generator is initialized with all symbol names and unresolved references that begin with an underscore, and it efficiently produces new, unique names by incrementing numeric suffixes or increasing leading underscores as needed. The TraverseScoping struct now holds an optional UidGenerator instead of a set of used names, and delegates UID creation to this generator. The new implementation ensures UIDs are allocated as Atoms using an arena allocator, and the logic is centralized for maintainability. Associated helper functions and test cases for the old logic are removed.

Possibly related issues

Possibly related PRs

  • refactor(traverse): remove get_unique_name_impl #10755: This PR replaces the inline unique name generation logic in crates/oxc_traverse/src/context/scoping.rs with a new UidGenerator struct from a dedicated uid module, removing all previous helper functions and centralizing UID creation, which supersedes the related PR’s removal of a wrapper function around the old unique name logic.
    """

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e0a8946 and 79e462d.

⛔ Files ignored due to path filters (1)
  • tasks/coverage/snapshots/semantic_typescript.snap is excluded by !**/*.snap
📒 Files selected for processing (6)
  • crates/oxc_traverse/src/context/mod.rs (1 hunks)
  • crates/oxc_traverse/src/context/scoping.rs (5 hunks)
  • crates/oxc_traverse/src/context/uid.rs (1 hunks)
  • tasks/transform_conformance/overrides/babel-plugin-transform-typescript/test/fixtures/namespace/same-name/output.mjs (1 hunks)
  • tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-identifier/output.js (1 hunks)
  • tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-member-expression/output.js (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/oxc_traverse/src/context/mod.rs
🚧 Files skipped from review as they are similar to previous changes (4)
  • tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-identifier/output.js
  • tasks/transform_conformance/overrides/babel-plugin-transform-typescript/test/fixtures/namespace/same-name/output.mjs
  • crates/oxc_traverse/src/context/scoping.rs
  • crates/oxc_traverse/src/context/uid.rs
🧰 Additional context used
🪛 Biome (1.9.4)
tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-member-expression/output.js

[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)

🔇 Additional comments (1)
tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-member-expression/output.js (1)

112-114: Correctly implemented variable renaming from UID generation optimization.

These variable renaming changes correctly reflect the expected output of the optimized UID generation algorithm mentioned in the PR. The variables have been renamed from _unbound, _bound, and _unbound2 to ___unbound2, ___bound2, and ___unbound3 respectively, while maintaining the same functionality.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
crates/oxc_traverse/src/context/scoping.rs (1)

287-294: Potential allocator mismatch – consider capturing the allocator once

generate_uid_name takes an &'a Allocator parameter every time it is called, yet the UidGenerator is initialised only on the first call and retains that allocator reference internally.
If the caller ever passes a different allocator on a later invocation, the parameter is silently ignored, which is surprising and could lead to hard-to-debug memory bugs (strings ending up in mixed arenas).

Two possible fixes:

- pub fn generate_uid_name(&mut self, name: &str, allocator: &'a Allocator) -> Atom<'a> {
+ pub fn generate_uid_name(&mut self, name: &str, allocator: &'a Allocator) -> Atom<'a> {
     // ..
 }
  1. Store the allocator in TraverseScoping at construction and remove the extra parameter:
- pub fn generate_uid_name(&mut self, name: &str, allocator: &'a Allocator) -> Atom<'a> {
-     let uid_generator =
-         self.uid_generator.get_or_insert_with(|| UidGenerator::new(&self.scoping, allocator));
+ pub fn generate_uid_name(&mut self, name: &str) -> Atom<'a> {
+     let uid_generator = self
+         .uid_generator
+         .get_or_insert_with(|| UidGenerator::new(&self.scoping, self.allocator));
  1. Alternatively, assert the allocator equality on subsequent calls to catch misuse early.

Either way clarifies the ownership model and prevents accidental allocator mixing.

crates/oxc_traverse/src/context/uid.rs (1)

140-152: Minor: U32_MAX_LEN constant off by one

const U32_MAX_LEN: usize = "4294967296".len();
u32::MAX is 4294967295 (10 digits). While the off-by-one doesn’t break correctness (overflowing parses are rejected anyway), consider documenting the intent or using:

const U32_MAX_LEN: usize = u32::MAX.to_string().len();

This expresses the limit directly and avoids magic numbers.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c753f75 and 6dbb1b0.

⛔ Files ignored due to path filters (1)
  • tasks/coverage/snapshots/semantic_typescript.snap is excluded by !**/*.snap
📒 Files selected for processing (6)
  • crates/oxc_traverse/src/context/mod.rs (1 hunks)
  • crates/oxc_traverse/src/context/scoping.rs (5 hunks)
  • crates/oxc_traverse/src/context/uid.rs (1 hunks)
  • tasks/transform_conformance/overrides/babel-plugin-transform-typescript/test/fixtures/namespace/same-name/output.mjs (1 hunks)
  • tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-identifier/output.js (1 hunks)
  • tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-member-expression/output.js (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-member-expression/output.js

[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)

⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Conformance
  • GitHub Check: Test wasm32-wasip1-threads
  • GitHub Check: Test NAPI
  • GitHub Check: Clippy
  • GitHub Check: Benchmark (isolated_declarations)
  • GitHub Check: Benchmark (semantic)
  • GitHub Check: Benchmark (formatter)
  • GitHub Check: Benchmark (minifier)
  • GitHub Check: Benchmark (codegen)
  • GitHub Check: Benchmark (parser)
  • GitHub Check: Benchmark (transformer)
  • GitHub Check: Benchmark (lexer)
  • GitHub Check: Test (ubuntu-latest)
  • GitHub Check: Test (macos-latest)
  • GitHub Check: Miri
  • GitHub Check: Build Linter Benchmark
🔇 Additional comments (7)
crates/oxc_traverse/src/context/mod.rs (1)

24-24: LGTM: Module import for new UID generation functionality.

Adding this module import integrates the newly created UID generation module into the context module's scope, supporting the refactoring effort.

tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-identifier/output.js (2)

1-1: LGTM: Variable renaming aligned with new UID generation approach.

The variable name change from _unbound to ___unbound2 reflects the improved UID generation algorithm which now uses triple underscores and numeric suffixes to avoid collisions.


8-8: LGTM: Consistent renaming in variable usage.

The variable reference is properly updated to match the declaration on line 1, maintaining consistency throughout the code.

tasks/transform_conformance/tests/babel-plugin-transform-exponentiation-operator/test/fixtures/assign-to-member-expression/output.js (2)

1-1: LGTM: Variable declarations updated with new naming convention.

The variable declarations now use triple underscores and numeric suffixes (___unbound2, ___bound2, ___unbound3) instead of single underscores, consistent with the improved UID generation algorithm.

🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)


[error] 1-1: This aliasing of this is unnecessary.

Arrow functions inherits this from their enclosing scope.

(lint/complexity/noUselessThisAlias)


112-114: LGTM: Consistent renaming in variable usage.

The variable references have been properly updated to use the new naming convention (___unbound2, ___bound2, ___unbound3), maintaining consistency with their declarations.

tasks/transform_conformance/overrides/babel-plugin-transform-typescript/test/fixtures/namespace/same-name/output.mjs (1)

1-22: LGTM: New test fixture with updated UID generation pattern.

This fixture demonstrates the new UID generation approach with consistent underscore-prefixed names and numeric suffixes for namespace identifiers. The nested namespace structure correctly preserves the TypeScript namespace semantics while using the improved naming convention.

crates/oxc_traverse/src/context/uid.rs (1)

248-266: Empty base name edge case

When name consists solely of underscores/digits (e.g. "_"), base becomes the empty string.
That works, but it means the empty string is a legitimate key in names. If any other part of the code assumes identifiers are non-empty, it might mis-behave.

Please double-check callers or add a short comment confirming an empty base is intentional and safe.

@overlookmotel overlookmotel force-pushed the 05-01-perf_transformer_faster_uid_generation branch from 6dbb1b0 to e0a8946 Compare May 2, 2025 00:17
@Boshen Boshen added the 0-merge Merge with Graphite Merge Queue label May 2, 2025
Copy link
Member
Boshen commented May 2, 2025

Merge activity

Alter the algorithm for generating UIDs, to improve its performance.

Previously we stored all existing symbol names which start with `_` in an `FxHashSet`. When creating a UID based on `foo`, it would first see if `_foo` is available, then try `_foo2`, then `_foo3`, then `_foo4` etc.

When creating a lot of UIDs from the same base name (`foo` in example above), this has poor performance as each attempt requires a separate hashset lookup.

Instead, use an `FxHashMap` mapping base name to:

1. Largest number of underscores at start.
2. Largest numeric prefix on end.

i.e. if there are existing symbols `_foo`, `_bar3`, `_bar8`, `_qux`, `___qux2`, this produces a map:

```
{
    "foo": { postfix: 1, underscore_count: 1 },
    "bar": { postfix: 8, underscore_count: 1 },
    "qux": { postfix: 2, underscore_count: 3 },
}
```

When generating a UID, `postfix` is incremented and UID is constructed as `<underscores><base><postfix>`.

This requires a maximum of 1 x hashmap lookup and 1 x hashmap insert for each UID. It also reduces the size of the hashmap where many UIDs are created for same base name.

This new algorithm produces almost same UIDs as Babel, but not quite. 3 tests require their outputs to be changed due to UIDs being different.
@graphite-app graphite-app bot force-pushed the 05-01-perf_transformer_faster_uid_generation branch from e0a8946 to 79e462d Compare May 2, 2025 01:15
@graphite-app graphite-app bot merged commit 79e462d into main May 2, 2025
27 checks passed
@graphite-app graphite-app bot removed the 0-merge Merge with Graphite Merge Queue label May 2, 2025
@graphite-app graphite-app bot deleted the 05-01-perf_transformer_faster_uid_generation branch May 2, 2025 01:23
@Boshen Boshen mentioned this pull request May 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-transformer Area - Transformer / Transpiler C-performance Category - Solution not expected to change functional behavior, only performance
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
0