Here is something I have been wondering about for a while. I think I know the answer, but I want to hear from some experts. It's mainly a question of efficiency and performance hit.
Let's say you have several 'For' loops back to back; Is it better declare the counter variable a single time in a function, and then reuse it over again for future 'For' loops within the same function, or declare and initialize for each 'For' loop.
Here is an example of what I mean, respectively.
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
void main()
{
sampleFunction();
}
void sampleFunction()
{
short counter;
for(counter = 0; counter < 10; counter++)
{
//---Insert code here
}
//--------Code
//--------Code
//--------Code
for(counter = 0; counter < 10; counter++)
{
//---Insert code here
}
//--------Code
//--------Code
//--------Code
//--------Code
for(counter = 0; counter < 10; counter++)
{
//---Insert code here
//---Insert code here
}
}
|
Versus........
Example 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
void main()
{
sampleFunction();
}
void sampleFunction()
{
for(short counter = 0; counter < 10; counter++)
{
//---Insert code here
}
//--------Code
//--------Code
//--------Code
for(short counter = 0; counter < 10; counter++)
{
//---Insert code here
}
//--------Code
//--------Code
//--------Code
//--------Code
for(short counter = 0; counter < 10; counter++)
{
//---Insert code here
//---Insert code here
}
}
|
My instincts tell me this:
Example 1 might run slightly faster since it only makes a single declaration and reuses that variable for the rest of the function. However, since it keeps that variable in memory for the entire function, it means more memory is consumed for the duration of the function, which also means less memory is available for execution of other code outside of the 'For' loops.
Example 2 might run a bit slower since it constantly has to find and set aside a spot in memory for each new declaration in a 'For' loop. However, since it releases the memory every time a 'For' loop ends, it means more memory is available for code execution outside of the 'For' loops.