Mike Wahler said:
Could you show a specific example please?
inline bool isLess(int a, int b)
{
return a < b;
}
template<class T>
struct Less : public binary_function<T, T, bool> {
bool operator()(const T& t1, const T& t2) const
{
return t1 < t2;
}
};
std::sort(vec.begin(), vec.end(), isLess); // #1
vs.
std::sort(vec.begin(), vec.end(), Less<int>()); // #2
This is an implementation detail, but for most implementations in
wide-use today, #1 will not be inlined, but #2 will. I've confirmed
this on VC++.net and gcc 3.3.2. Try it for yourself and see.
Also, take a look at the following sources:
"Function objects are usually faster than ordinary functions. The
concept
of templates usually allows better optimization because more details
are
defined at compile time. Thus passing function objects instead of
ordinary
functions [to Standard Library algorithms] often results in better
performance." Josuttis, C++ Standard Library, Sec. 5.9, p. 127.
"A suitably-defined object serves as well as - and often better than -
a
function. For example, it is easier to inline the application
operator of a
class than to inline a function passed as a pointer to a function.
Consequently, function objects often execute faster than do ordinary
functions." Stroustrup, TC++PL (3d. ed.), Sec. 18.4, p. 515.
"Interestingly, if you were to compare the performance of the two
calls to
sort (one using greater<double>, one using doubleGreater [an ordinary
function declared inline]), you'd almost certainly find that the one
using
greater<double> was faster. For instance, I timed the two calls to
sort on
..... four different STL platforms, each set to optimize for speed, and
the
version using greater<double> was faster every time. . . . Because
[doubleGreater] is a pointer to a function, each time it's used inside
sort,
compilers make an indirect function call. . . . 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." Meyers, Effective STL,
Item
46, pps. 202-03.
There was a thread on this clc++m last month:
http://groups.google.com/[email protected]&frame=off
Best regards,
Tom