From 705e19f7942001c2bf7734273c34a34d21fcd1c1 Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Sat, 27 Jul 2024 10:25:40 +0000 Subject: [PATCH] perf(sourcemap): reduce memory copies encoding JSON (#4489) Reduce memory copies when encoding source map as JSON, extending approach taken in #4476 to also avoid memory copies for source texts. I believe reason this shows no benefit on benchmarks is because our benchmarks only create a source map from a single source file, but it should result in a speed-up when there are multiple sources. --- crates/oxc_sourcemap/src/encode.rs | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/crates/oxc_sourcemap/src/encode.rs b/crates/oxc_sourcemap/src/encode.rs index 79614f0f05f70..eaacbc9a1bfe5 100644 --- a/crates/oxc_sourcemap/src/encode.rs +++ b/crates/oxc_sourcemap/src/encode.rs @@ -31,6 +31,7 @@ pub fn encode_to_string(sourcemap: &SourceMap) -> Result { let mut contents = PreAllocatedString::new( 10 + sourcemap.names.len() * 2 + sourcemap.sources.len() * 2 + + sourcemap.source_contents.as_ref().map_or(0, |sources| sources.len() * 2 + 1) + if let Some(x) = &sourcemap.x_google_ignore_list { x.len() * 2 } else { 0 }, ); @@ -58,21 +59,15 @@ pub fn encode_to_string(sourcemap: &SourceMap) -> Result { contents.push("],\"sourcesContent\":[".into()); cfg_if::cfg_if! { if #[cfg(feature = "concurrent")] { - let quote_source_contents = source_contents + let quoted_source_contents: Vec<_> = source_contents .par_iter() - .map(|x| serde_json::to_string(x.as_ref())) - .collect::, serde_json::Error>>() - .map_err(Error::from)?; + .map(to_json_string) + .collect(); + contents.push_list(quoted_source_contents.into_iter())?; } else { - let quote_source_contents = source_contents - .iter() - .map(|x| serde_json::to_string(x.as_ref())) - .collect::, serde_json::Error>>() - .map_err(Error::from)?; + contents.push_list(source_contents.iter().map(to_json_string))?; } }; - - contents.push(quote_source_contents.join(",").into()); } if let Some(x_google_ignore_list) = &sourcemap.x_google_ignore_list {