c++ - Would std::count_if be faster without an if? -
here's gcc std::count_if
code
template<typename _inputiterator, typename _predicate> typename iterator_traits<_inputiterator>::difference_type count_if(_inputiterator __first, _inputiterator __last, _predicate __pred) { [snip] typename iterator_traits<_inputiterator>::difference_type __n = 0; (; __first != __last; ++__first) if (__pred(*__first)) ++__n; homecoming __n; }
my question: work improve (i.e., faster) use
__n += __pred(*__first); // instead of if statement
this version add, doesn't branch.
the replacement gave is not equivalent, because there far fewer restrictions on predicate think:
anything can used in conditional context (can contextually convertedbool
), valid return-type predicate (an explicit
conversion bool
enough). that return-type can react funny beingness added iterators difference-type. 25 algorithms library [algorithms]
25.1 general [algorithms.general]
8 predicate
parameter used whenever algorithm expects function object (20.9) that, when applied result of dereferencing corresponding iterator, returns value testable true
. in other words, if algorithm takes predicate pred
argument , first
iterator argument, should work correctly in build pred(*first)
contextually converted bool
(clause 4). function object pred
shall not apply non-constant function through dereferenced iterator.
the homecoming giving replacement indigestion standard integer-type, , value neither 0 nor 1.
also, maintain in mind compilers can optimize nowadays (and c++ ones need to, template-stuff layered deep).
c++ performance gcc stl
No comments:
Post a Comment