title: Optimizing sum of elements in array
body: <p>My code is as follows:</p>
  
  <pre><code>double a,b; //These variable are inputs to the function
  double *inArr; //This is also an iput to the function whose size is NumElements
  double *arr = new double[numElements]; //NumElements is ~ 10^6
  double sum = 0.0;
  for(unsigned int i=0;i&lt;numElements;++i)
  {
      double k = a*inArr[i] + b; //This doesn't take any time
      double el = arr[i]; //This doesn't take any time
      el *= k; //This doesn't take any time
      sum += el; //This takes a long time!!!
  }
  </code></pre>
  
  <p>This code goes over the elements of an array each time calculating a value k, for each element it adds k times that element to sum. I separated the code into so many steps so that when my profiler tells me which line takes a long time I will know exactly which calculation is the culprit. My profiler tells me that adding el to sum is what's slowing down my program (this might seem a little strange that a simple addition would be slow but I call this function hundreds of times and each time it performs millions of calculations). My only theory is that because sum is in a different scope operations using it take longer. So I edited the code to be: </p>
  
  <pre><code>double a,b; //These variable are inputs to the function
  double *inArr; //This is also an iput to the function whose size is NumElements
  double *arr = new double[numElements]; //NumElements is ~ 10^6
  double sum = 0.0;
  for(unsigned int i=0;i&lt;numElements;++i)
  {
      double k = a*inArr[i] + b; //This doesn't take any time
      double el = arr[i]; //This doesn't take any time
      el *= k; //This doesn't take any time
      double temp = sum + el; //This doesn't take any time
      sum = el; //This takes a long time!!!
  }
  </code></pre>
  
  <p>And now the sum operation takes very little time even though it accesses the sum variable. The assignment takes a long time now. Is my theory correct that the reason this happens is that it takes longer to assign to variables that aren't in the current scope? If so why is that true? Is there any way to make this assignment work quickly? I know I can optimize this using parallelization, I want to know if I can do any better serially. I am using VS 2012 running in release mode, I am using the VS performance analyzer as a profiler.</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>Once I removed the optimization it turns out that the access to inArr is what is taking the most time.</p>