Wednesday, November 13, 2019

c++ - Is it efficient to declare a variable in a loop?




If I do one of the following (which I assume are equivalent for the purpose of this question)



for(int i=0; i{
//... do stuff
for(int j=0; j {

//... do stuff
}
//... do stuff
}

for(int i=0; i{
int j;
//... do stuff
}



Does the variable j get recreated on the stack every loop (is the SP constantly being updated every loop), or is the compiler smart enough to know how many local variables a function might have at one time, and then makes room for all of them on the stack at function entry?



I understand that this is theoretically compiler-dependent, but I assume simple things like this are common across all major compilers. If not, does someone know specifically about GCC and VC++ compilers?


Answer



I believe the variables will only be created once, although I do not care and I don't believe you should either.



This is likely an example of pre-optimization (or unnecessary optimization) on your part; the potential inefficiency created by declaring variables within a loop is incredibly small and "optimizing" your code by declaring variables in different locations will have a negligible impact on the overall runtime and memory usage of your program.




Consider spending time optimizing your algorithms and finding efficient data structures, as this will likely be a much better use of your time.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...