From a913fc64d2f179dfcf7b11895f5b6c7c24d6979c Mon Sep 17 00:00:00 2001 From: Kevin Ballard Date: Mon, 19 Jan 2015 10:21:58 -0800 Subject: [PATCH 1/2] Add benchmark for String::shrink_to_fit() This uses `Vec::shrink_to_fit()` internally so it's really benchmarking that. --- src/libcollections/string.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 5d35d8a86795a..e15bfdf912bbd 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -1408,4 +1408,20 @@ mod tests { let _ = String::from_utf8_lossy(s.as_slice()); }); } + + #[bench] + fn bench_exact_size_shrink_to_fit(b: &mut Bencher) { + let s = "Hello there, the quick brown fox jumped over the lazy dog! \ + Lorem ipsum dolor sit amet, consectetur. "; + // ensure our operation produces an exact-size string before we benchmark it + let mut r = String::with_capacity(s.len()); + r.push_str(s); + assert_eq!(r.len(), r.capacity()); + b.iter(|| { + let mut r = String::with_capacity(s.len()); + r.push_str(s); + r.shrink_to_fit(); + r + }); + } } From c384ee18fcb55274682e8a9a24608bfc825bedce Mon Sep 17 00:00:00 2001 From: Kevin Ballard Date: Mon, 19 Jan 2015 10:15:17 -0800 Subject: [PATCH 2/2] 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) --- src/libcollections/vec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 689d96b4b2955..4c25c9866e473 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -356,7 +356,7 @@ impl Vec { } self.cap = 0; } - } else { + } else if self.cap != self.len { unsafe { // Overflow check is unnecessary as the vector is already at // least this large.