Note that there are some explanatory texts on larger screens.

plurals
  1. POPolicy vs polymorphic speed
    primarykey
    data
    text
    <p>I read that using a policy class for a function that will be called in a tight loop is much faster than using a polymorphic function. However, I setup this demo and the timing indicates that it is exactly the opposite!? The policy version takes between 2-3x longer than the polymorphic version.</p> <pre><code>#include &lt;iostream&gt; #include &lt;boost/timer.hpp&gt; // Policy version template &lt; typename operation_policy&gt; class DoOperationPolicy : public operation_policy { using operation_policy::Operation; public: void Run(const float a, const float b) { Operation(a,b); } }; class OperationPolicy_Add { protected: float Operation(const float a, const float b) { return a + b; } }; // Polymorphic version class DoOperation { public: virtual float Run(const float a, const float b)= 0; }; class OperationAdd : public DoOperation { public: float Run(const float a, const float b) { return a + b; } }; int main() { boost::timer timer; unsigned int numberOfIterations = 1e7; DoOperationPolicy&lt;OperationPolicy_Add&gt; policy_operation; for(unsigned int i = 0; i &lt; numberOfIterations; ++i) { policy_operation.Run(1,2); } std::cout &lt;&lt; timer.elapsed() &lt;&lt; " seconds." &lt;&lt; std::endl; timer.restart(); DoOperation* polymorphic_operation = new OperationAdd; for(unsigned int i = 0; i &lt; numberOfIterations; ++i) { polymorphic_operation-&gt;Run(1,2); } std::cout &lt;&lt; timer.elapsed() &lt;&lt; " seconds." &lt;&lt; std::endl; } </code></pre> <p>Is there something wrong with the demo? Or is just incorrect that the policy should be faster?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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