I have the following code with two functions, one that allocates a static array and one that allocates an array on the stack. The functions are run many many times and their execution time calculated. The stack allocation is consistently (marginally) faster than the static allocation. I was under the impression that because a static variable is bound before run time that it would execute faster than the array that is allocated on the stack
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ARRAY 8192
void statArray()
{
static int statArray[MAX_ARRAY];
}
void stackArray()
{
int stackArray[MAX_ARRAY];
}
int main(int argc, char * argv[]) {
clock_t start, end;
double staticTime, stackTime;
int i;
int comparisons = 5000000;
start = clock();
for (i = 0; i < comparisons; i++) {
statArray();
}
end = clock()-start;
staticTime = (double)end / CLOCKS_PER_SEC;
start = clock();
for (i = 0; i < comparisons; i++) {
stackArray();
}
end = clock() - start;
stackTime = (double) end / CLOCKS_PER_SEC;
Thanks
disassembled statArray
0x0000000000400594 <+0>: push %rbp
0x0000000000400595 <+1>: mov %rsp,%rbp
0x0000000000400598 <+4>: leaveq
0x0000000000400599 <+5>: retq
disassembled stackArray
0x000000000040059a <+0>: push %rbp
0x000000000040059b <+1>: mov %rsp,%rbp
0x000000000040059e <+4>: sub $0x7f88,%rsp
0x00000000004005a5 <+11>: leaveq
0x00000000004005a6 <+12>: retq
retq.