views:

137

answers:

4

Hello. I'm reading the book about optimization teckniks. There is not much description or advices in example though. Here's the thing:

int agag(int a)
{
  static int dfdfdf = 0;
  static int prev_resilt = 0;
  if (dfdfdf == a)
    return prev_result;
  dfdfdf = a;
  a = SomeCalcs();
  prev_result = a;
  return a;
}

The key thing is: if the arguments are the same as in previous calculation, it will return previous result immediately avoiding a hard calculation. The question is: will these two static variables be existing until the end of program? As i understand, it is a bad thing to have a lot of these?

I know it's not much optimization. But i'm only concerned about influence of static variables..

Thank you very much for the answers!

A: 

Yep, they exist until your program ends. You're ok as long as you're sure that an a input of 0 has a result of 0.

Jim Buck
+6  A: 

The memory used by the static variables will be allocated in the data segment instead of in the heap or stack. This only becomes a problem when you have a large number of static variables since it means that the executable will have to load a much larger data segment from disk.

But the biggest problem with this method is that it only stores a single value. Better to just implement proper memoization if you expect many repeats with the same inputs.

Ignacio Vazquez-Abrams
too many local variables increases the stack, local globals (statics) are in the data segment, so more controllable and predictable. Have to be equally careful with too many of either type.
dwelch
+7  A: 

Yes, the lifetime of static variables is until the end of the program.

However, doing this adds state to your function. This makes it non-thread-safe, harder to debug, and harder to test. These are generally considered bad things.

Oli Charlesworth
A: 

You forgot to assign dfdfdf with a, among other small mistakes.

Yes, the two variables will take up memory for the lifetime of the program, as if they were globals. They will probably use 8 bytes. The code of function agag takes up more space than that and will not be reclaimed until the end of the program either. Why don't you worry about that?

Pascal Cuoq
The code takes up no runtime storage space because the copy in memory coincides with the copy in the filesystem cache, and can be discarded and reloaded at any time...not to mention it's shared between processes. That's very different from data.
R..
Yes, sorry about that. The original code was a little different. I was concentrating only on "new" result part and totally forgot to restore dfdfdf = a;
Kane