I wonder in C, in the case a function is called a huge amount of times, if a static array is faster to deal with than a non-static array.
First case: Non-static int array of 10 int:
void useNonStaticIntArray(int i){
int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
array[i] = i;
}
int main(void){
int i;
for (i = 0; i < 1000000000; i++) {
useNonStaticIntArray(i % 10);
}
return 0;
}
Second case: static int array of 10 int:
void useStaticIntArray(int i){
static int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
array[i] = i;
}
int main(void){
int i;
for (i = 0; i < 1000000000; i++) {
useStaticIntArray(i % 10);
}
return 0;
}
Third case: Non-static int
void nonStaticInt(int i){
int a;
a = i;
}
int main(void){
int i;
for (i = 0; i < 1000000000; i++) {
nonStaticInt(i % 10);
}
return 0;
}
Fourth case: static int
void staticInt(int i){
int a;
a = i;
}
int main(void){
int i;
for (i = 0; i < 1000000000; i++) {
staticInt(i % 10);
}
return 0;
}
So I've done some testing on a Debian virtual box:
1)
time ./a.out
real 0m7.733s
user 0m7.696s
sys 0m0.008s
2):
time ./a.out
real 0m5.477s
user 0m5.416s
sys 0m0.008s
3)
time ./a.out
real 0m5.764s
user 0m5.736s
sys 0m0.000s
4)
time ./a.out
real 0m7.189s
user 0m7.016s
sys 0m0.032s
So it looks like the static is faster than the non-static, I tested several times to be sure and it seems to always (for the 10 times I tested) be the case.
Now I have 3 questions: - Have I done something wrong that falsify the results ? (They were what I expected) - Is it always the case no matter the size of the array ? (from 1 to N, N -> max stack possible value) - How does it really work ?
How does it really work ?- inspect the assembly generated by the compiler.staticyou change the semantics of the array quite considerably. And if it's not curiosity have you measured in your real program that this is a top-three bottleneck of your program? And did you build with optimization enabled before measuring (in your real program, since the code you show will be optimized to empty programs)?nonStaticIntandstaticIntare exactly the same in the third and fourth case.