Lazy construction - virtual method vs. if-then to stub a getter
<p>The background to my problem is that I'm trying to create a lazy grid structure, where areas of the grid are only instantiated when required, otherwise they return a default value when queried.  </p>

<p>Boiling down the problem a little, consider the following mockup of my situation:</p>

<pre><code>struct Container {
  std::vector&lt;Base&gt; data;

  float get(int indexOuter, int indexInner) {
     return data[indexOuter].get(indexInner);
  }
}
</code></pre>

<p>I want to stub the <code>Base::get</code> function in some cases to always return the same value, whereas in other cases I want to return the value in some array.  I imagine two possible solutions.  </p>

<p>The first solution is to use a flag on <code>Base</code>, i.e.</p>

<pre><code>struct Base {
  std::vector&lt;float&gt; data;

  float get(int indexInner) {
    if (data.empty()) return 0;
    return data[indexInner];
  }
}
</code></pre>

<p>This solution would involve destroying <code>data</code> (resize to zero) when the object enters "stub mode", and recreating <code>data</code> when the object is once again concrete.  </p>

<p>The second solution I can think of is inheritance, i.e.</p>

<pre><code>struct Container {
  std::vector&lt;Base*&gt; data;

  float get(int indexOuter, int indexInner) {
     return data[indexOuter]-&gt;get(indexInner);
  }
}
struct Base {
  virtual float get(int indexInner) = 0;
}
struct Stub : public Base {
  float get(int indexInner) {
    return 0;
  }   
}
struct Concrete : public Base {
  std::vector&lt;float&gt; data;

  float get(int indexInner) {
    return data[indexInner];
  }   
}
</code></pre>

<p>and then replace instances of <code>Concrete</code> with instances of <code>Stub</code>, and vice versa, in the <code>Container</code>'s <code>data</code> array when necessary (taking care to ensure clean destruction).</p>

<p>The question is one of performance.  <code>Container::get</code> will be called 1000s of times a second, maybe more.  However, <code>Base</code>s entering/exiting "stub mode" will occur far less frequently.</p>

<p>With the two solutions proposed above, the first solution involves an additional if-then clause, whereas the second solution involves an indirection from the <code>Base</code> pointer to the object, plus an indirection from the abstract method to the derived implementation.</p>

<p>Which of these solutions would give the best performance?  Are there any other more-performant solutions I have not considered?</p>