Optimize empty case in Vec::retain

This commit is contained in:
John Spray 2024-07-26 15:58:24 +01:00
parent 355efacf0d
commit 6a6824a0ab
1 changed files with 6 additions and 0 deletions

View File

@ -1711,6 +1711,12 @@ impl<T, A: Allocator> Vec<T, A> {
F: FnMut(&mut T) -> bool,
{
let original_len = self.len();
if original_len == 0 {
// Empty case: explicit return allows better optimization, vs letting compiler infer it
return;
}
// Avoid double drop if the drop guard is not executed,
// since we may make some holes during the process.
unsafe { self.set_len(0) };