Note that there are some explanatory texts on larger screens.

plurals
  1. POstd::function vs template
    primarykey
    data
    text
    <p>Thanks to C++11 we received the <code>std::function</code> family of functor wrappers. Unfortunately, I keep hearing only bad things about these new additions. The most popular is that they are horribly slow. I tested it and they truly suck in comparison with templates.</p> <pre><code>#include &lt;iostream&gt; #include &lt;functional&gt; #include &lt;string&gt; #include &lt;chrono&gt; template &lt;typename F&gt; float calc1(F f) { return -1.0f * f(3.3f) + 666.0f; } float calc2(std::function&lt;float(float)&gt; f) { return -1.0f * f(3.3f) + 666.0f; } int main() { using namespace std::chrono; const auto tp1 = system_clock::now(); for (int i = 0; i &lt; 1e8; ++i) { calc1([](float arg){ return arg * 0.5f; }); } const auto tp2 = high_resolution_clock::now(); const auto d = duration_cast&lt;milliseconds&gt;(tp2 - tp1); std::cout &lt;&lt; d.count() &lt;&lt; std::endl; return 0; } </code></pre> <p>111 ms vs 1241 ms. I assume this is because templates can be nicely inlined, while <code>function</code>s cover the internals via virtual calls.</p> <p>Obviously templates have their issues as I see them:</p> <ul> <li>they have to be provided as headers which is not something you might not wish to do when releasing your library as a closed code,</li> <li>they may make the compilation time much longer unless <code>extern template</code>-like policy is introduced,</li> <li>there is no (at least known to me) clean way of representing requirements (concepts, anyone?) of a template, bar a comment describing what kind of functor is expected.</li> </ul> <p>Can I thus assume that <code>function</code>s can be used as <em>de facto</em> standard of passing functors, and in places where high performance is expected templates should be used?</p> <hr> <p>Edit:</p> <p>My compiler is the Visual Studio 2012 <em>without</em> CTP.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload