Skip to content

Commit 977c44a

Browse files
committed
Auto merge of #21401 - kballard:optimize-shrink-to-fit, r=nikomatsakis
Don't reallocate when capacity is already equal to length `Vec::shrink_to_fit()` may be called on vectors that are already the correct length. Calling out to `reallocate()` in this case is a bad idea because there is no guarantee that `reallocate()` won't allocate a new buffer anyway, and based on performance seen in external benchmarks, it seems likely that it is in fact reallocating a new buffer. Before: test string::tests::bench_exact_size_shrink_to_fit ... bench: 45 ns/iter (+/- 2) After: test string::tests::bench_exact_size_shrink_to_fit ... bench: 26 ns/iter (+/- 1)
2 parents 59dcba5 + c384ee1 commit 977c44a

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/libcollections/string.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1413,4 +1413,20 @@ mod tests {
14131413
let _ = String::from_utf8_lossy(s.as_slice());
14141414
});
14151415
}
1416+
1417+
#[bench]
1418+
fn bench_exact_size_shrink_to_fit(b: &mut Bencher) {
1419+
let s = "Hello there, the quick brown fox jumped over the lazy dog! \
1420+
Lorem ipsum dolor sit amet, consectetur. ";
1421+
// ensure our operation produces an exact-size string before we benchmark it
1422+
let mut r = String::with_capacity(s.len());
1423+
r.push_str(s);
1424+
assert_eq!(r.len(), r.capacity());
1425+
b.iter(|| {
1426+
let mut r = String::with_capacity(s.len());
1427+
r.push_str(s);
1428+
r.shrink_to_fit();
1429+
r
1430+
});
1431+
}
14161432
}

src/libcollections/vec.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ impl<T> Vec<T> {
356356
}
357357
self.cap = 0;
358358
}
359-
} else {
359+
} else if self.cap != self.len {
360360
unsafe {
361361
// Overflow check is unnecessary as the vector is already at
362362
// least this large.

0 commit comments

Comments
 (0)