inline bool mycmp(int i, int j) {
return (i < j);
}
class mycmp2 {
public:
bool operator()(int i, int j) {
return (i < j);
}
};
above is my example. I want know why the functor one is faster than the inline funcion!
//test example:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
struct CompareFunctor {
bool operator()(int a, int b) const {
return a < b;
}
};
inline bool compareFunction(int a, int b) {
return a < b;
}
int main() {
std::vector<int> nums(10000000);
std::generate(nums.begin(), nums.end(), std::rand);
{
std::vector<int> numsObj = nums;
clock_t start = clock();
std::sort(numsObj.begin(), numsObj.end(), CompareFunctor());
clock_t end = clock();
double duration = (double)(end - start) / CLOCKS_PER_SEC;
std::cout << "use functor:" << duration << " second" << std::endl;
}
{
std::vector<int> numsFunc = nums;
clock_t start = clock();
std::sort(numsFunc.begin(), numsFunc.end(), compareFunction);
clock_t end = clock();
double duration = (double)(end - start) / CLOCKS_PER_SEC;
std::cout << "use inline function:" << duration << " second" << std::endl;
}
return 0;
}
Translation: "The above is the code I used for testing, and the result shows that the functor is faster. I would like to know why. It seems that the functor is also an inline function at the underlying level. Is there any optimization performed by the compiler?"