Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vectorize slice::is_sorted #132883

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion library/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
Loading