inline bool mycmp(int i, int j) {
return (i < j);
}
class mycmp2 {
public:
bool operator()(int i, int j) {
return (i < j);
}
};
上面是我的例子。 我想知道为什么函子比内联函数更快!
//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;
}
翻译:“上面是我测试用的代码,结果显示functor速度更快,我想知道为什么,看来functor底层也是内联函数,有没有什么优化由编译器执行?”
看来函子在底层也是一个内联函数。编译器有没有进行任何优化?
默认情况下,如果类函数直接在类声明中定义,则相当于标记为内联。请注意,内联只是编译器的信息,您不能强制函数内联:由编译器决定。