title: Is it faster to allocate memory statically once or allocate dynamically?
body: <p>I am a graduate student in Mechanical Engineering. My research group has an in-house finite element code written in C++. I have noticed that a lot of the memory for vectors and arrays is allocated statically, for example:</p>
  
  <p>In Element.h</p>
  
  <pre><code>// A vector to store a finite element residual vector in h file
  static Real* sRe
  </code></pre>
  
  <p>In Element.C</p>
  
  <pre><code>if ( ! sIsResAndJacAllocated )
  {
      UInt numElemDofs = this-&gt;GetNumDofs();
      // Residual storage
      sReXt         = new Real[numElemDofs*numElemDofs];
      sIsResAndJacAllocated = true;
  }
  </code></pre>
  
  <p>In this manner, the vector is only allocated once for the first element that reaches this function, and the rest of the objects just use that memory space repeatedly.</p>
  
  <p>The first person to start developing the code knew more C than C++, that's why a lot of it is written this way.</p>
  
  <p>The idea behind allocating these vectors and arrays statically in the group is that it is faster to allocate these big pieces of memory just once and use it repeatedly; in comparison to having to allocate the same array multiple times for each finite element or every time the function gets called (using alloca for example). Is this true? Is there really a big speed difference?</p>
  
  <p>We are trying to reach a conclusion about this in order to decide if we should keep the static memory allocation or get rid of it. I have been looking for an answer to this for a few weeks now with no luck. I hope your opinion will help reach a conclusion.</p>
  
  <p>Thanks.</p>
  
  <p>Hernan</p>