C "Static" Optimization
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 (dfdf开发者_JAVA百科df == 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.
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.
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
.
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?
精彩评论