Skip to content

Commit

Permalink
refactor(transformer/async-to-generator): avoid allocating unnecessar…
Browse files Browse the repository at this point in the history
…y `Atom`s (#7975)

Remove several `Atom` allocations from this function.

1. Take a `Cow<'a, str>` instead of `&str`, and use `AstBuilder::atom_from_cow` to avoid reallocating the string when possible.
2. Create a static `Atom` for `"_"` (no allocation required, as `"_"` is a `&'static str`).
3. `name` is an `ArenaString`, so already in arena. Convert `name` to `Atom` directly with `Atom::from`, instead of `AstBuilder::atom` (which makes a 2nd copy of the string in arena).
  • Loading branch information
overlookmotel committed Dec 18, 2024
1 parent 8b7c5ae commit d4d7bc0
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions crates/oxc_transformer/src/es2017/async_to_generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
//! * Babel implementation: <https://github.com/babel/babel/blob/v7.26.2/packages/babel-plugin-transform-async-to-generator>
//! * Async / Await TC39 proposal: <https://github.com/tc39/proposal-async-await>
use std::mem;
use std::{borrow::Cow, mem};

use oxc_allocator::{Box as ArenaBox, String as ArenaString};
use oxc_ast::{ast::*, AstBuilder, Visit, NONE};
Expand Down Expand Up @@ -534,15 +534,16 @@ impl<'a, 'ctx> AsyncGeneratorExecutor<'a, 'ctx> {
/// // Reserved keyword
/// * `this` -> `_this`
/// * `arguments` -> `_arguments`
fn normalize_function_name(input: &str, ast: AstBuilder<'a>) -> Atom<'a> {
if !is_reserved_keyword(input) && is_identifier_name(input) {
return ast.atom(input);
fn normalize_function_name(input: &Cow<'a, str>, ast: AstBuilder<'a>) -> Atom<'a> {
let input_str = input.as_ref();
if !is_reserved_keyword(input_str) && is_identifier_name(input_str) {
return ast.atom_from_cow(input);
}

let mut name = ArenaString::with_capacity_in(input.len() + 1, ast.allocator);
let mut name = ArenaString::with_capacity_in(input_str.len() + 1, ast.allocator);
let mut capitalize_next = false;

let mut chars = input.chars();
let mut chars = input_str.chars();
if let Some(first) = chars.next() {
if is_identifier_start(first) {
name.push(first);
Expand All @@ -563,12 +564,14 @@ impl<'a, 'ctx> AsyncGeneratorExecutor<'a, 'ctx> {
}

if name.is_empty() {
return ast.atom("_");
} else if is_reserved_keyword(name.as_str()) {
return Atom::from("_");
}

if is_reserved_keyword(name.as_str()) {
name.insert(0, '_');
}

ast.atom(name.into_bump_str())
Atom::from(name)
}

/// Creates a [`Function`] with the specified params, body and scope_id.
Expand Down

0 comments on commit d4d7bc0

Please sign in to comment.