title: optimize output value using a class and public member
body: <p>Suppose you have a function, and you call it a lot of times, every time the function return a big object. I've optimized the problem using a functor that return <code>void</code>, and store the returning value in a public member:</p>
  
  <pre><code>#include &lt;vector&gt;
  const int N = 100;
  
  std::vector&lt;double&gt; fun(const std::vector&lt;double&gt; &amp; v, const int n)
  {
      std::vector&lt;double&gt; output = v;
      output[n] *= output[n];
      return output;
  }
  
  class F
  {
  public:
      F() : output(N) {};
      std::vector&lt;double&gt; output;
      void operator()(const std::vector&lt;double&gt; &amp; v, const int n)
   {
       output = v;
       output[n] *= n;
    }
  };
  
  
  int main()
  {
      std::vector&lt;double&gt; start(N,10.);
      std::vector&lt;double&gt; end(N);
      double a;
  
      // first solution
      for (unsigned long int i = 0; i != 10000000; ++i)
        a = fun(start, 2)[3];
  
      // second solution
      F f;
      for (unsigned long int i = 0; i != 10000000; ++i)
      {
       f(start, 2);
       a = f.output[3];
   }
  }
  </code></pre>
  
  <p>Yes, I can use inline or optimize in an other way this problem, but here I want to stress on this problem: with the functor I declare and construct the output variable <code>output</code> only one time, using the function I do that every time it is called. The second solution is two time faster than the first with <code>g++ -O1</code> or <code>g++ -O2</code>. What do you think about it, is it an ugly optimization?</p>
  
  <p>Edit:</p>
  
  <p>to clarify my aim. I have to evaluate the function >10M times, but I need the output only few random times. It's important that the input is not changed, in fact I declared it as a const reference. In this example the input is always the same, but in real world the input change and it is function of the previous output of the function.</p>