Home > Software engineering >  Static var in loop could be way to optimize in c ?
Static var in loop could be way to optimize in c ?

Time:09-24

I think non-static var in loop could make some overhead (construct / destruct for each loop). Am I right? then why we don't use static var in main-loop?

for(;;){
  type1 var1;
  type2 var2;
//(var1, var2 construct here )

....
   // Do something
....
  
//(var1, var2 destruct here )
}
for(;;){
  static type1 var1;
  static type2 var2;

//(var1, var2 don't construct here )
....
   // Do something
....
  
//(var1, var2 don't destruct here )
}

CodePudding user response:

Your second snippet is not thread safe. These days, you always need to consider thread safety as computational gains have moved from faster clock speeds to more processor cores.

You can trust a compiler to optimise out the first snippet. If you're ever in doubt, check the generated assembly.

  • Related