Std :: function performance compared to templates

I looked at another question regarding std :: function and why it is slow, but I'm still not convinced / don't understand. I ran the program from a question with a few changes.

#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;
}

When using the standardized version, the code starts after 4 seconds, but when using the std :: function, the execution time increases to 15 seconds. I understand why copying the std :: function can be expensive, but here, even with passing the link, it seems there is no difference, can anyone explain why this is happening?

Just for reference, this is the output when I introduce g ++ -version

Apple LLVM version 7.0.2 (clang-700.1.81)
+4
source share
1 answer

( -O3) calc1, 0,0 . , . , , .

( -O3) calc2 ( std::function), 2 . , , , . std::function ( , , . ), ( ) , std::function ( , , ).


std::function , , std::function. , , "", .

, "" , . , std::function. , , .cpp , calc2 std::function. , std::function , . , , , . - std::function, .

+3

Source: https://habr.com/ru/post/1621053/


All Articles