As far as good practices are concerned, it would be best to declare the variable in the smallest / most restricted scope that you can (in this case within the loop if it is not going to be used anywhere else). Makes the code easier to maintain (eg, you do not have to upload 100 lines to see what type the variable x was initialized) and in some cases the compiler could apply some optimization method.
Now from the performance point of view, it will depend to a large extent on the compiler (and the language) that you use and you would have to do tests to see which one is better. Modern compilers are responsible for optimize the generated code , so the result should be very similar (if not equal) in both cases.
... That was the theory, now let's see the practice. I have created three test cases (although perhaps not in the most scientific way) with loops that are repeated 10 million times and I have executed them 20 times to see the results. This is the code:
Case 1: statement inside the loop
#include <stdio.h>
int main() {
int x = 0;
for (x = 0; x < 10000000; x++) {
char array[255] = "";
array[0] = (char) (65 + (x%23));
//printf("%s\n", array);
}
return 0;
}
Case 2: Declaration outside the loop, emptying with loop for
#include <stdio.h>
int main() {
int x = 0;
char array[255];
for (x = 0; x < 10000000; x++) {
int y;
for (y = 0; y < 255; y++) {
array[y] = 0;
}
array[0] = (char) (65 + (x%23));
//printf("%s\n", array);
}
return 0;
}
Case 3: Declaration outside the loop, emptied with memset
#include <stdio.h>
#include <string.h>
int main() {
char array[255];
int x = 0;
for (x = 0; x < 10000000; x++) {
memset(array,0,255);
array[0] = (char) (65 + (x%23));
//printf("%s\n", array);
}
return 0;
}
And the results were (drum roll):
- Case 1 - 0.1587 seconds
- Case 2 - 6.1470 seconds
- Case 3 - 0.1413 seconds
Which is a bit ******** because it pulls down all part of the theory I put up. For the first and third case it would be fulfilled, but not for the second case (surely I did something wrong ... or I have the worst compiler in the world that is also quite possible).