From d4d7bc08d3252977b874c1403c8816582bde9584 Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Wed, 18 Dec 2024 02:25:36 +0000 Subject: [PATCH] refactor(transformer/async-to-generator): avoid allocating unnecessary `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). --- .../src/es2017/async_to_generator.rs | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/oxc_transformer/src/es2017/async_to_generator.rs b/crates/oxc_transformer/src/es2017/async_to_generator.rs index 49f4a6515245b..8ecd6981bfc07 100644 --- a/crates/oxc_transformer/src/es2017/async_to_generator.rs +++ b/crates/oxc_transformer/src/es2017/async_to_generator.rs @@ -51,7 +51,7 @@ //! * Babel implementation: //! * Async / Await TC39 proposal: -use std::mem; +use std::{borrow::Cow, mem}; use oxc_allocator::{Box as ArenaBox, String as ArenaString}; use oxc_ast::{ast::*, AstBuilder, Visit, NONE}; @@ -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); @@ -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.