title: Optimizing a quadruple nested "for" loop
body: <p>I'm developing a 2D numerical model in c++, and I would like to speed up a specific member function that is slowing down my code. The function is required to loop over every <code>i,j</code> grid point in the model and then perform a double summation at every grid point over <code>l</code> and <code>m</code>. The function is as follows:</p>
  
  <pre><code>int Class::Function(void) {
      double loadingEta;
      int i,j,l,m;
  
      //etaLatLen=64, etaLonLen=2*64
      //l_max = 12
  
      for (i=0; i&lt;etaLatLen; i++) {
          for (j=0; j &lt; etaLonLen; j++) {
              loadingEta = 0.0;
              for (l=0; l&lt;l_max+1; l++) {
                  for (m=0; m&lt;=l; m++) {
                      loadingEta += etaLegendreArray[i][l][m] * (SH_C[l][m]*etaCosMLon[j][m] + SH_S[l][m]*etaSinMLon[j][m]);
                  }
              }
              etaNewArray[i][j] = loadingEta;
          }
      }
  
      return 1;
  }
  </code></pre>
  
  <p>I've been trying to change the loop order to speed things up, but to no avail. Any help would be much appreciated. Thank you!</p>
  
  <p>EDIT 1:</p>
  
  <p>All five arrays are allocated in the constructor of my class as follows:</p>
  
  <pre><code>etaLegendreArray = new double**[etaLatLen];
  for (int i=0; i&lt;etaLatLen; i++) {
      etaLegendreArray[i] = new double*[l_max+1];
      for (int l=0; l&lt;l_max+1; l++) {
          etaLegendreArray[i][l] = new double[l_max+1];
      }
  }
  
  SH_C = new double*[l_max+1];
  SH_S = new double*[l_max+1];
  for (int i=0; i&lt;l_max+1; i++) {
      SH_C[i] = new double[l_max+1]; 
      SH_S[i] = new double[l_max+1];
  }
  
  etaCosMLon = new double*[etaLonLen];
  etaSinMLon = new double*[etaLonLen];
  for (int j=0; j&lt;etaLonLen; j++) {
      etaCosMLon[j] = new double[l_max+1];
      etaSinMLon[j] = new double[l_max+1];
  }
  </code></pre>
  
  <p>Perhaps it would be better if these were 1D arrays instead of multidimensional?</p>