From 2fd9ac4a7ba43868791af24210c1684019665687 Mon Sep 17 00:00:00 2001 From: Laiho Date: Sun, 10 Nov 2024 23:55:04 +0200 Subject: [PATCH] vectorize slice::is_sorted --- core/src/slice/mod.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/core/src/slice/mod.rs b/core/src/slice/mod.rs index dbcfe94644017..0009aa682be25 100644 --- a/core/src/slice/mod.rs +++ b/core/src/slice/mod.rs @@ -4093,7 +4093,23 @@ impl [T] { where T: PartialOrd, { - self.is_sorted_by(|a, b| a <= b) + // This odd number works the best. 32 + 1 extra due to overlapping chunk boundaries. + const CHUNK_SIZE: usize = 33; + if self.len() < CHUNK_SIZE { + return self.windows(2).all(|w| w[0] <= w[1]); + } + let mut i = 0; + // Check in chunks for autovectorization. + while i < self.len() - CHUNK_SIZE { + let chunk = &self[i..i + CHUNK_SIZE]; + if !chunk.windows(2).fold(true, |acc, w| acc & (w[0] <= w[1])) { + return false; + } + // We need to ensure that chunk boundaries are also sorted. + // Overlap the next chunk with the last element of our last chunk. + i += CHUNK_SIZE - 1; + } + self[i..].windows(2).all(|w| w[0] <= w[1]) } /// Checks if the elements of this slice are sorted using the given comparator function.