Skip to content

Commit

Permalink
add explanation, fix test
Browse files Browse the repository at this point in the history
  • Loading branch information
llogiq committed Jan 24, 2017
1 parent b40432c commit bfabe81
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/libcore/iter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,17 @@ impl<I: Iterator, P> Iterator for Filter<I, P> where P: FnMut(&I::Item) -> bool
(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;
Expand Down
2 changes: 1 addition & 1 deletion src/libcoretest/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down

0 comments on commit bfabe81

Please sign in to comment.