I looked at another stack overflow question regarding std::function and why it is slow but I am still not convinced/do not understand. I ran the program from the question with a few modifications.
#include <iostream>
#include <functional>
#include <string>
#include <chrono>
template <typename F>
float calc1(F f) { return -1.0f * f(3.3f) + 666.0f; }
float calc2(const std::function<float (float)>& f) { return -1.0f * f(3.3f) + 666.0f; }
int main() {
std::function<float (float)> f = [](float arg){ return arg * 0.5f; };
for (int i = 0; i < 1e9; ++i) {
// calc2(f);
calc1([](float arg){ return arg * 0.5f; });
}
return 0;
}
With the templated version, the code runs in 4 seconds but with the std::function involved the runtime increases to 15 seconds. I understand why copying a std::function can be expensive, but here even with passing a reference, there seems to be no difference, could someone explain why this happens?
Just for reference this is the output when I type in g++ --version
Apple LLVM version 7.0.2 (clang-700.1.81)