As I knew from the book Effective C++, it would have a better performance if I pass a Function Object by its value rather than function reference or function pointer in C++. So how does the modern compiler do to optimize that kind of scenario?
Or let's say usually we do not recommend to pass an object of our self-customized class by value, but as function object is actually the same as a normal object but just implemented the "operator()" inside the class. So, there must be something different for the compiler to treat these two things when passing them by value, right?
Below is a case giving a comparison between the function object and function pointer.
#include <algorithm>
#include <vector>
#include <ctime>
#include <iostream>
bool cmp(int a, int b) { return a < b; }
int main() {
std::vector<int> v(10000000);
for (size_t i = 0; i < 10000000; ++i)
v.push_back(rand());
std::vector<int> v2(v);
std::sort(v.begin(), v.end(), std::less<int>()); // This way would be faster than below;
std::sort(v2.begin(), v2.end(), cmp);
}
Aucun commentaire:
Enregistrer un commentaire