Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2fd9ac4

Browse files
committedNov 10, 2024
vectorize slice::is_sorted
1 parent 63a4a9b commit 2fd9ac4

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed
 

‎core/src/slice/mod.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -4093,7 +4093,23 @@ impl<T> [T] {
40934093
where
40944094
T: PartialOrd,
40954095
{
4096-
self.is_sorted_by(|a, b| a <= b)
4096+
// This odd number works the best. 32 + 1 extra due to overlapping chunk boundaries.
4097+
const CHUNK_SIZE: usize = 33;
4098+
if self.len() < CHUNK_SIZE {
4099+
return self.windows(2).all(|w| w[0] <= w[1]);
4100+
}
4101+
let mut i = 0;
4102+
// Check in chunks for autovectorization.
4103+
while i < self.len() - CHUNK_SIZE {
4104+
let chunk = &self[i..i + CHUNK_SIZE];
4105+
if !chunk.windows(2).fold(true, |acc, w| acc & (w[0] <= w[1])) {
4106+
return false;
4107+
}
4108+
// We need to ensure that chunk boundaries are also sorted.
4109+
// Overlap the next chunk with the last element of our last chunk.
4110+
i += CHUNK_SIZE - 1;
4111+
}
4112+
self[i..].windows(2).all(|w| w[0] <= w[1])
40974113
}
40984114

40994115
/// Checks if the elements of this slice are sorted using the given comparator function.

0 commit comments

Comments
 (0)
Failed to load comments.