Skip to content

Commit

Permalink
Don't reallocate when capacity is already equal to length
Browse files Browse the repository at this point in the history
`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)
  • Loading branch information
lilyball committed Jan 19, 2015
1 parent a913fc6 commit c384ee1
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion src/libcollections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,7 @@ impl<T> Vec<T> {
}
self.cap = 0;
}
} else {
} else if self.cap != self.len {
unsafe {
// Overflow check is unnecessary as the vector is already at
// least this large.
Expand Down

0 comments on commit c384ee1

Please sign in to comment.