Skip to content

Commit

Permalink
vectorize slice::is_sorted
Browse files Browse the repository at this point in the history
  • Loading branch information
LaihoE committed Nov 10, 2024
1 parent 63a4a9b commit 2fd9ac4
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4093,7 +4093,23 @@ impl<T> [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.
Expand Down

0 comments on commit 2fd9ac4

Please sign in to comment.