From 5d510999d8a766a2cae48354448488b846c0518e Mon Sep 17 00:00:00 2001
From: John Spray <john@neon.tech>
Date: Fri, 26 Jul 2024 15:58:24 +0100
Subject: [PATCH] Optimize empty case in Vec::retain

---
 alloc/src/vec/mod.rs | 6 ++++++
 1 file changed, 6 insertions(+)

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<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) };