Predicate for STL algorithms: template function vs functor

I found for such predicate, both of the following works:
1
2
3
4
5
6
7
8
9
10
11
12
// template function
template<typename T>
bool Pred(const T& x, const T& y) {
	return x == 3*y;
}

// functor
struct Pred : public std::binary_function<int, int, bool> {
	bool operator()(int x, int y) {
		return x == 3 * y;
	}
};


Which one is better in term of performance. Why should we prefer one over the other? Thanks.
Last edited on
The functor will always be slower because an object must be constructed, I would say. Furthermore, STL algorithms take the #"%&%$!! functor by value, meaning you must make sure you have a proper copy constructor.

Now, how much more slower functors are? Probably not noticeable by many standards. I bet only the most demanding of scenarios would care about performance difference.
Last edited on
It seems that STL algorithms DO NOT take the functor by value. I tested the following code which works:
1
2
3
4
5
6
7
struct Pred : public std::binary_function<int, int, bool> {
	bool operator()(int x, int y) {
		return x == 3 * y;
	}
private:
	Pred (const ThreeTimes&);
};
Last edited on
I have used functors twice and the algorithm I used took them by value both times.
Topic archived. No new replies allowed.