add explanation, fix test

This commit is contained in:
Andre Bogus 2017-01-24 09:46:01 +01:00
parent b40432c949
commit bfabe817de
2 changed files with 12 additions and 1 deletions

View File

@ -1100,6 +1100,17 @@ fn size_hint(&self) -> (usize, Option<usize>) {
(0, upper) // can't know a lower bound, due to the predicate
}
// this special case allows the compiler to make `.filter(_).count()`
// branchless. Barring perfect branch prediction (which is unattainable in
// the general case), this will be much faster in >90% of cases (containing
// virtually all real workloads) and only a tiny bit slower in the rest.
//
// Having this specialization thus allows us to write `.filter(p).count()`
// where we would otherwise write `.map(|x| p(x) as usize).sum()`, which is
// less readable and also less backwards-compatible to Rust before 1.10.
//
// Using the branchless version will also simplify the LLVM byte code, thus
// leaving more budget for LLVM optimizations.
#[inline]
fn count(mut self) -> usize {
let mut count = 0;

View File

@ -194,7 +194,7 @@ fn test_iterator_enumerate_count() {
#[test]
fn test_iterator_filter_count() {
let xs = [0, 1, 2, 3, 4, 5, 6, 7, 8];
assert_eq!(xs.iter().filter(|x| x % 2 == 0).count(), 5);
assert_eq!(xs.iter().filter(|&&x| x % 2 == 0).count(), 5);
}
#[test]