Skip to content

Commit 74147b8

Browse files
committed
Use the length limit as the initial capacity
The length limit turns out to be a surprisingly good heuristic for initial allocation size. See here for more details [1]. [1]: #88173 (comment)
1 parent 09f0876 commit 74147b8

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/librustdoc/html/length_limit.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,18 @@ pub(super) struct HtmlWithLimit {
2929
impl HtmlWithLimit {
3030
/// Create a new buffer, with a limit of `length_limit`.
3131
pub(super) fn new(length_limit: usize) -> Self {
32+
let buf = if length_limit > 1000 {
33+
// If the length limit is really large, don't preallocate tons of memory.
34+
String::new()
35+
} else {
36+
// The length limit is actually a good heuristic for initial allocation size.
37+
// Measurements showed that using it as the initial capacity ended up using less memory
38+
// than `String::new`.
39+
// See https://github.com/rust-lang/rust/pull/88173#discussion_r692531631 for more.
40+
String::with_capacity(length_limit)
41+
};
3242
Self {
33-
buf: String::new(),
43+
buf,
3444
len: 0,
3545
limit: length_limit,
3646
unclosed_tags: Vec::new(),

src/librustdoc/html/markdown.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1096,7 +1096,6 @@ fn markdown_summary_with_limit(
10961096
let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
10971097
let mut p = LinkReplacer::new(p, link_names);
10981098

1099-
// FIXME: capacity
11001099
let mut buf = HtmlWithLimit::new(length_limit);
11011100
let mut stopped_early = false;
11021101
p.try_for_each(|event| {

0 commit comments

Comments
 (0)