Quote:
... It may thus come as a surprise to learn that passing STL function objects - objects masquerading as functions - to algorithms typically yields code that is more efficient than passing real functions.
... The explanation for this behavior is simple: inlining. If a function object's operator() function has been declared inline (either explicitly via inline or implicitly by defining it in its class definition), the body of that function is available to compilers, and most compilers will happily inline that function during template instantiation of the called algorithm. ... As a result, sort contains zero function calls and compilers are able to perform optimizations that on this call-free code that are otherwise not usually attempted.
... This situation is different for the call to sort using [a real function]. To see how it's different, we must recall that there's no such thing as passing a function as a parameter to another function. When we try to pass a function as a parameter, compiloers silently convert the function into a pointer to that function, and it's the pointer we actually pass. ... each time [the real function is] used inside sort, compilers make an indirect function call - a call through a pointer. Most compilers won't try to inline calls to functions that are invoked through function pointers, even if, as in this example, such functions have been declared inline and the optimization appears to be straightforward. ...
The fact that function pointer parameters inhibit inlining explains an observation that long-time C programmers often find hard to believe: C++'s sort virtually always embarrasses C's qsort when it comes to speed. ... In my tests on a vector of a million doubles, it ran up to 670% faster...
Please address all comments to Scott Meyers, not to me.