Skip to content

Commit 369a9dc

Browse files
committed
Remove boundary checks in slice comparison operators
In order to get rid of all range checks, the compiler needs to explicitly see that the slices it iterates over are as long as the loop variable upper bound. This further improves the performance of slice comparison: ``` test u8_cmp ... bench: 4,761 ns/iter (+/- 1,203) test u8_lt ... bench: 4,579 ns/iter (+/- 649) test u8_partial_cmp ... bench: 4,768 ns/iter (+/- 761) test u16_cmp ... bench: 4,607 ns/iter (+/- 580) test u16_lt ... bench: 4,681 ns/iter (+/- 567) test u16_partial_cmp ... bench: 4,607 ns/iter (+/- 967) test u32_cmp ... bench: 4,448 ns/iter (+/- 891) test u32_lt ... bench: 4,546 ns/iter (+/- 992) test u32_partial_cmp ... bench: 4,415 ns/iter (+/- 646) test u64_cmp ... bench: 4,380 ns/iter (+/- 1,184) test u64_lt ... bench: 5,684 ns/iter (+/- 602) test u64_partial_cmp ... bench: 4,663 ns/iter (+/- 1,158) ```
1 parent bf9254a commit 369a9dc

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

src/libcore/slice.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1561,9 +1561,11 @@ impl<T: Ord> Ord for [T] {
15611561
#[inline]
15621562
fn cmp(&self, other: &[T]) -> Ordering {
15631563
let l = cmp::min(self.len(), other.len());
1564+
let lhs = &self[..l];
1565+
let rhs = &other[..l];
15641566

15651567
for i in 0..l {
1566-
match self[i].cmp(&other[i]) {
1568+
match lhs[i].cmp(&rhs[i]) {
15671569
Ordering::Equal => (),
15681570
non_eq => return non_eq,
15691571
}
@@ -1578,9 +1580,11 @@ impl<T: PartialOrd> PartialOrd for [T] {
15781580
#[inline]
15791581
fn partial_cmp(&self, other: &[T]) -> Option<Ordering> {
15801582
let l = cmp::min(self.len(), other.len());
1583+
let lhs = &self[..l];
1584+
let rhs = &other[..l];
15811585

15821586
for i in 0..l {
1583-
match self[i].partial_cmp(&other[i]) {
1587+
match lhs[i].partial_cmp(&rhs[i]) {
15841588
Some(Ordering::Equal) => (),
15851589
non_eq => return non_eq,
15861590
}

0 commit comments

Comments
 (0)