title: Virtual Functions and Performance C++
body: <p>Before you cringe at the duplicate title, the other question wasn't suited to what I ask here (IMO). So.</p>
  
  <p>I am really wanting to use virtual functions in my application to make things a hundred times easier (isn't that what OOP is all about ;)). But I read somewhere they came at a performance cost, seeing nothing but the same old contrived hype of premature optimization, I decided to give it a quick whirl in a small benchmark test using:</p>
  
  <p><em>CProfiler.cpp</em></p>
  
  <pre><code>#include "CProfiler.h"
  
  CProfiler::CProfiler(void (*func)(void), unsigned int iterations) {
      gettimeofday(&amp;a, 0);
      for (;iterations &gt; 0; iterations --) {
          func();
      }
      gettimeofday(&amp;b, 0);
      result = (b.tv_sec * (unsigned int)1e6 + b.tv_usec) - (a.tv_sec * (unsigned int)1e6 + a.tv_usec);
  };
  </code></pre>
  
  <p><em>main.cpp</em></p>
  
  <pre><code>#include "CProfiler.h"
  
  #include &lt;iostream&gt;
  
  class CC {
    protected:
      int width, height, area;
    };
  
  class VCC {
    protected:
      int width, height, area;
    public:
      virtual void set_area () {}
    };
  
  class CS: public CC {
    public:
      void set_area () { area = width * height; }
    };
  
  class VCS: public VCC {
    public:
      void set_area () {  area = width * height; }
    };
  
  void profileNonVirtual() {
      CS *abc = new CS;
      abc-&gt;set_area();
      delete abc;
  }
  
  void profileVirtual() {
      VCS *abc = new VCS;
      abc-&gt;set_area();
      delete abc;
  }
  
  int main() {
      int iterations = 5000;
      CProfiler prf2(&amp;profileNonVirtual, iterations);
      CProfiler prf(&amp;profileVirtual, iterations);
  
      std::cout &lt;&lt; prf.result;
      std::cout &lt;&lt; "\n";
      std::cout &lt;&lt; prf2.result;
  
      return 0;
  }
  </code></pre>
  
  <p>At first I only did 100 and 10000 iterations, and the results were worrying: 4ms for non virtualised, and 250ms for the virtualised! I almost went "nooooooo" inside, but then I upped the iterations to around 500,000; to see the results become almost completely identical (maybe 5% slower without optimization flags enabled).</p>
  
  <p>My question is, why was there such a significant change with a low amount of iterations compared to high amount? Was it purely because the virtual functions are hot in cache at that many iterations?</p>
  
  <p><em>Disclaimer</em><br>
  I understand that my 'profiling' code is not perfect, but it, as it has, gives an estimate of things, which is all that matters at this level. Also I am asking these questions to learn, not to solely optimize my application.</p>