Callback Dispatch: std::function vs Template Parameter
Question 39 / 51 • Correct so far: 0 (0 answered)
Std Function Callback
int accumulate(const std::vector<int>& v,
const std::function<int(int, int)>& fn) {
int acc = 0;
for (int x : v) acc = fn(acc, x);
return acc;
}
int result = accumulate(values, add); Template Callback
template <typename Fn>
int accumulate(const std::vector<int>& v, Fn fn) {
int acc = 0;
for (int x : v) acc = fn(acc, x);
return acc;
}
int result = accumulate(values, add); Shared test data (shared-setup)
constexpr int kN = 1024;
static std::vector<int> values(kN);
struct ValuesInit {
ValuesInit() { std::iota(values.begin(), values.end(), 1); }
} _values_init; Which snippet is faster?
Snippet B is faster. std::function invokes the callable indirectly through a stored function pointer, adding per-call overhead; larger callables also incur a heap allocation. A template parameter lets the compiler inline the lambda directly, eliminating the indirect dispatch and enabling further optimisations such as auto-vectorisation.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Std Function Callback | 1.4 us | 1.0× |
| Template Callback | 20.9 ns | 66.8× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.