Micro-optimization for string format (#95774)

I get this is a bit of a silly change in some ways. It isn't going to
have some massive impact. But using dhat I got these stats on a smallish
sample nextjs project

| metric | A (parse.rs change) | B (baseline) | delta |
| ------------------------ | -------------------- | ------------ |
------------------- |
| total bytes allocated | 438.4 MiB | 442.6 MiB | -4.3 MiB (-0.94%) |
| total allocation count | 1,672,688 | 1,872,347 | -199,659 (-10.66%)

Eliminating ~200k allocations from this small change just felt worth it.
This commit is contained in:
Jimmy Miller
2026-07-27 16:28:29 -04:00
committed by GitHub
parent 8399ee9150
commit 0df0a5e4f1
@@ -36,7 +36,7 @@ use turbo_tasks::{PrettyPrintError, ResolvedVc, ValueToString, Vc, turbofmt, uti
use turbo_tasks_fs::{FileContent, FileSystemPath, rope::Rope};
use turbo_tasks_hash::hash_xxh3_hash64;
use turbopack_core::{
SOURCE_URL_PROTOCOL,
SOURCE_URL_PROTOCOL_STR,
asset::{Asset, AssetContent},
issue::{Issue, IssueExt, IssueSeverity, IssueSource, IssueStage, StyledString},
source::Source,
@@ -250,7 +250,14 @@ impl SourceMapGenConfig for InlineSourcesContentConfig {
fn file_name_to_source(&self, f: &FileName) -> String {
match f {
FileName::Custom(s) => {
format!("{SOURCE_URL_PROTOCOL}///{s}")
// format! here is suboptimal and allocates over and over again.
// On a random test next test project this one spot accounted for
// 10% of allocations, hence the more verbose approach.
let mut out = String::with_capacity(SOURCE_URL_PROTOCOL_STR.len() + 3 + s.len());
out.push_str(SOURCE_URL_PROTOCOL_STR);
out.push_str("///");
out.push_str(s);
out
}
_ => f.to_string(),
}