Use with_capacity in rewrite_path

It not only makes rustfmt faster, but also makes the code nicer imo.

performance:
```
Summary
  ./build/host/stage2/bin/rustfmt library/std/src/lib.rs --edition 2021 ran
    1.03 ± 0.02 times faster than ../rust3/build/host/stage2/bin/rustfmt library/std/src/lib.rs --edition 2021
```

Final string lengths when formatting `core`:
```
143144 counts
(  1)    23535 (16.4%, 16.4%): 4
(  2)    16138 (11.3%, 27.7%): 3
(  3)    15143 (10.6%, 38.3%): 5
(  4)    13477 ( 9.4%, 47.7%): 6
(  5)     9122 ( 6.4%, 54.1%): 7
(  6)     8715 ( 6.1%, 60.2%): 1
(  7)     6321 ( 4.4%, 64.6%): 8
(  8)     6178 ( 4.3%, 68.9%): 11
(  9)     5826 ( 4.1%, 73.0%): 2
( 10)     5168 ( 3.6%, 76.6%): 9
( 11)     4162 ( 2.9%, 79.5%): 10
( 12)     3555 ( 2.5%, 82.0%): 13
( 13)     3337 ( 2.3%, 84.3%): 14
( 14)     3017 ( 2.1%, 86.4%): 17
( 15)     2875 ( 2.0%, 88.4%): 12
( 16)     2345 ( 1.6%, 90.1%): 15
( 17)     1956 ( 1.4%, 91.4%): 16
( 18)     1946 ( 1.4%, 92.8%): 18
( 19)     1410 ( 1.0%, 93.8%): 19
( 20)     1187 ( 0.8%, 94.6%): 20
( 21)     1045 ( 0.7%, 95.3%): 22
( 22)     1042 ( 0.7%, 96.1%): 21
( 23)      792 ( 0.6%, 96.6%): 23
( 24)      649 ( 0.5%, 97.1%): 24
( 25)      619 ( 0.4%, 97.5%): 27
( 26)      569 ( 0.4%, 97.9%): 28
( 27)      540 ( 0.4%, 98.3%): 26
( 28)      460 ( 0.3%, 98.6%): 25
( 29)      328 ( 0.2%, 98.8%): 29
( 30)      243 ( 0.2%, 99.0%): 31
[...]
```
This commit is contained in:
Nilstrieb 2024-05-23 21:09:26 +02:00 committed by Yacin Tmimi
parent d5f1200ed6
commit 28e43b6fb4

View File

@ -43,11 +43,13 @@ pub(crate) fn rewrite_path(
) -> Option<String> {
let skip_count = qself.as_ref().map_or(0, |x| x.position);
let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
"::".to_owned()
} else {
String::new()
};
// 32 covers almost all path lengths measured when compiling core, and there isn't a big
// downside from allocating slightly more than necessary.
let mut result = String::with_capacity(32);
if path.is_global() && qself.is_none() && path_context != PathContext::Import {
result.push_str("::");
}
let mut span_lo = path.span.lo();