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!
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.