Invoking an std::function requires a few more operations than a lambda

Calling a std::function is generally a bit slower than executing a lambda as a little more code is involved, for example, executing 1 million function calls for a std::vector of the explicit lambda type versus a std::vector of a corresponding std::function as follows.

Benchmark invocation without capture of lambda vs std::function:

Lambda std::function
auto test_direct_lambda() {  auto lbd = [](int v) {    return v * 3;  };  using L = decltype(lbd);  auto fs = std::vector<L>{};  fs.resize(1’000’000, lbd);   auto res = int{0};  for (const auto& f: fs) {    res = f(res);  }   return res;}
auto test_std_function() {  auto lbd = [](int v) {    return v * 3;   };  using F = std::function<int(int)>; ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.