From b2728931d188e66c67cae923d715ee9f7affd20f Mon Sep 17 00:00:00 2001 From: Dunqing <29533304+Dunqing@users.noreply.github.com> Date: Thu, 20 Mar 2025 08:54:52 +0000 Subject: [PATCH] perf(mangler, minifier): initialize a Vec with a specific value using `Vec::from_iter_in` combined with `repeat_with` (#9908) https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=a7c0cc8b2427a67e50259253a85d0cbd Replace `std::iter::from_fn` with `repeat_with` because it accepts a function that expects to return an `Option`, but we always return a `Some`, and it doesn't satisfy the `TrustedLen` trait. --- crates/oxc_mangler/src/lib.rs | 10 +++++----- .../src/peephole/substitute_alternate_syntax.rs | 6 ++++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/oxc_mangler/src/lib.rs b/crates/oxc_mangler/src/lib.rs index d43bea1b8cbf6..99389f4ae05bd 100644 --- a/crates/oxc_mangler/src/lib.rs +++ b/crates/oxc_mangler/src/lib.rs @@ -1,4 +1,4 @@ -use std::iter; +use std::iter::{self, repeat_with}; use fixedbitset::FixedBitSet; use itertools::Itertools; @@ -373,10 +373,10 @@ impl Mangler { allocator: &'a Allocator, ) -> Vec<'a, SlotFrequency<'a>> { let root_scope_id = scoping.root_scope_id(); - let mut frequencies = Vec::with_capacity_in(total_number_of_slots, allocator); - for _ in 0..total_number_of_slots { - frequencies.push(SlotFrequency::new(allocator)); - } + let mut frequencies = Vec::from_iter_in( + repeat_with(|| SlotFrequency::new(allocator)).take(total_number_of_slots), + allocator, + ); for (symbol_id, slot) in slots.iter().copied().enumerate() { let symbol_id = SymbolId::from_usize(symbol_id); diff --git a/crates/oxc_minifier/src/peephole/substitute_alternate_syntax.rs b/crates/oxc_minifier/src/peephole/substitute_alternate_syntax.rs index 95eef6eb0349f..87f5f69535bcd 100644 --- a/crates/oxc_minifier/src/peephole/substitute_alternate_syntax.rs +++ b/crates/oxc_minifier/src/peephole/substitute_alternate_syntax.rs @@ -1,3 +1,5 @@ +use std::iter::repeat_with; + use oxc_allocator::{CloneIn, Vec}; use oxc_ast::{NONE, ast::*}; use oxc_ecmascript::constant_evaluation::DetermineValueType; @@ -744,8 +746,8 @@ impl<'a> PeepholeOptimizations { if n.value.fract() == 0.0 { let n_int = n.value as usize; if (1..=6).contains(&n_int) { - let elisions = std::iter::from_fn(|| { - Some(ArrayExpressionElement::Elision(ctx.ast.elision(n.span))) + let elisions = repeat_with(|| { + ArrayExpressionElement::Elision(ctx.ast.elision(n.span)) }) .take(n_int); return Some(ctx.ast.expression_array(