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.
This commit is contained in:
overlookmotel 2024-07-27 10:25:40 +00:00
parent c958a557fe
commit 705e19f794

View file

@ -31,6 +31,7 @@ pub fn encode_to_string(sourcemap: &SourceMap) -> Result<String> {
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<String> {
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::<std::result::Result<Vec<_>, 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::<std::result::Result<Vec<_>, 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 {