diff --git a/alloc/src/vec/mod.rs b/alloc/src/vec/mod.rs index 729d5dd4fe4d2..417b88bfe8dad 100644 --- a/alloc/src/vec/mod.rs +++ b/alloc/src/vec/mod.rs @@ -1711,6 +1711,12 @@ impl Vec { 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) };