From b0ca5ff43264227bf18c6290cf6823a6985e3d31 Mon Sep 17 00:00:00 2001 From: Arthur Carcano Date: Tue, 11 Jul 2023 16:58:02 +0200 Subject: [PATCH] Add a short-circuiting path to slice comparison This adds a short-circuiting path to slice comparison using the fact that two slices of the same length and pointing at the same address are equal. --- library/core/src/slice/cmp.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/library/core/src/slice/cmp.rs b/library/core/src/slice/cmp.rs index 7601dd3c75608..7691a524dd349 100644 --- a/library/core/src/slice/cmp.rs +++ b/library/core/src/slice/cmp.rs @@ -87,7 +87,8 @@ where // SAFETY: `self` and `other` are references and are thus guaranteed to be valid. // The two slices have been checked to have the same size above. unsafe { - let size = mem::size_of_val(self); + let size = + if self.as_ptr() == other.as_ptr().cast() { 0 } else { mem::size_of_val(self) }; memcmp(self.as_ptr() as *const u8, other.as_ptr() as *const u8, size) == 0 } }