Search code examples
c++optimizationstatic-variables

Defining a static global array to avoid defining it in a function


I've just started working with a chunk of code that the authors claim is "highly optimized". At some point they do this:

namespace somename 
{ 
  static float array[N]; 
} 

float Someclass::some_function(std::vector<float>& input) 
{
  // use somename::array in some way 
  return result; 
}

The authors haven't included somename::array in the class because of issues with persistence code (which we have little control over). The class does O(N^2) operations on the array when some_function is called. So If I move array inside the function call,

float Someclass::some_function(std::vector<float>& input) 
{
  float array[N];
  // use somename::array in some way 
  return result; 
}

is it reasonable to expect a decrease in performance? In other words, is it obvious that, across many different systems and compilers, the author's optimization (using a global array rather than one inside the function) will help performance?


Solution

  • Since numbers matter:

    ./trial2.out 59.08s user 0.01s system 88% cpu 1:07.01 total

    ./trial.out 59.40s user 0.00s system 99% cpu 59.556 total

    The source code: http://pastebin.com/YA2WpTSU (With alternate code commented and tested)

    So, no difference. Compiled with:

    gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
    

    Time results while using a non-static array within the function:

    ./trial.out  57.32s user 0.04s system 97% cpu 58.810 total
    
    ./trial.out  57.77s user 0.04s system 97% cpu 59.259 total
    

    So again, no difference. Since when you use a array it is part of your function stack and not heap, there is no overhead with reserving memory every time the function is called. It would be an entirely different scenario in case you used a dynamic allocation (in which case, I do suspect that there would have been a huge difference in performance).