std::sort Comparator: Function Pointer vs Lambda
Question 35 / 51 • Correct so far: 0 (0 answered)
Func Ptr Sort
bool descending(int a, int b) { return a > b; }
void sortData(std::vector<int>& data, bool (*cmp)(int, int)) {
std::sort(data.begin(), data.end(), cmp);
}
sortData(data, cmp); Lambda Sort
void sortData(std::vector<int>& data) {
std::sort(data.begin(), data.end(), [](int a, int b) { return a > b; });
}
sortData(data); Shared test data (shared-setup)
constexpr int kDataSize = 4096;
static std::vector<int> makeData() {
std::mt19937 rng(42);
std::uniform_int_distribution<int> dist(0, 100000);
std::vector<int> v(kDataSize);
for (auto& x : v) x = dist(rng);
return v;
}
static const std::vector<int> BASE_DATA = makeData(); Which snippet is faster?
Snippet B is faster. A lambda has a unique type, so std::sort is instantiated with the comparator body directly visible and every comparison is inlined. A function pointer has type bool(*)(int,int): when its value is opaque at the call site the compiler cannot inline through it, leaving an indirect call per comparison throughout the entire sort.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Func Ptr Sort | 73.7 us | 1.0× |
| Lambda Sort | 25.7 us | 2.9× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.