learning_dude
learning_dude

Reputation: 1050

What is the performance of nested function within loops, considering variable definition inside the loop?

I have a question regarding performance, specifically on how it looks affected when we have some nested functionn calls within loops and many variable definitions inside the deepest function call. For example, lets say we have the folliwing:

void fun2(){

for(int i = 0 i<FINITE_NUMBER; i++){
 int a = 5*i; 
 int b = 6*i;
 .
 .
 //A HUGE LIST
 .
 .
 int zz = N*i;

 /* some operations with a,b,..z */

 //also, BESIDES THE SCOPE, what difference in performance would it make to declare a,b,...,zz outside of the for-loop?
 }
}

void fun1(){
   fun2();
}


int main(){

 for(;;){
  fun1();
 }
}

My understanding is that every time that fun1() finishes, the scope of all the initialized variables within fun2() will be destroyed as, having to initialize them again in the next loop cycle. So, would it be better to get rid of the function nesting? **please note my question in the comment inside fun2() definition.

Also, will the compiler optimization -Os would notice this?

Thanks in advance, please let me know if Im not clear enough with my question!

Upvotes: 0

Views: 530

Answers (1)

dash-o
dash-o

Reputation: 14452

Almost all compilers will be able to optimize the code (gcc, icc, clang) - the location of the declaration inside/outside the loop will not have impact. Better to keep the code logical and organized, and try to keep declaration and initialization close.

Thing that may help the compiler are

  • const (on variables) and
  • restrict (on pointers).
  • Block Scoped variables, indicating that values do not have to be persist between sections of the code.

They give the compiler extra information and flexibility to rearrange the code.

Upvotes: 3

Related Questions