martedì 4 dicembre 2012

Global, local and static variables: which is the faster?

This is the first post of the Questions&Answers series. With the tag QeA I'll collect all the relevant answer I'm posting in international forum on C/C++. Hope you'll enjoy it!

The answer is: "Static variable are faster then global and local variables." Moreover, there is no difference between global and local variables, because both are allocated in the stack and must be popped from the stack every time you use them. Let see together a practical demonstration of it!

If we consider the following simple source code:

1
2
3
4
5
6
7
8
9
10
11
12
static int a;
int fTest();
int main() {
  int b;
  a=a+11;
  b=b+22;
}
int fTest(){
  int c;
  c=c+33;
}

compiling it using gcc with option -S give us the following:

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
 .file "variabili.c"
 .def ___main; .scl 2; .type 32; .endef
 .text
.globl _main
 .def _main; .scl 2; .type 32; .endef
_main:
 pushl %ebp
 movl %esp, %ebp
 subl $8, %esp
 andl $-16, %esp
 movl $0, %eax
 addl $15, %eax
 addl $15, %eax
 shrl $4, %eax
 sall $4, %eax
 movl %eax, -8(%ebp)
 movl -8(%ebp), %eax
 call __alloca
 call ___main
 addl $11, _a
 leal -4(%ebp), %eax
 addl $22, (%eax)
 leave
 ret
.globl _fTest
 .def _fTest; .scl 2; .type 32; .endef
_fTest:
 pushl %ebp
 movl %esp, %ebp
 subl $4, %esp
 leal -4(%ebp), %eax
 addl $33, (%eax)
 leave
 ret
.lcomm _a,16

Note that we used int constants 11, 22 and 33 to easily identify the fragment of assembler code of interest. 
We can observe that:
  1. For what concern the global variable b and the local variable c, they are both popped from the stack and then the addition is performed;
  2. For what concern the static int variable a the compiler use the addl instruction with the absolute address of the space reserved to the variable a with the .lcomm _a,16 assembly directive.
In conclusion, it seems that static variable perform better than global and local variables.
Q.E.D. :)

Nessun commento:

Posta un commento