Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static vs global in terms of speed and space consumption in C

I would like to know difference between static variables and global variables in terms of access speed and space consumption. (If you want to know my platform: gcc compiler on Windows. (I am using Cygwin with Triton IDE for ARM7 embedded programming on windows. Triton comes with gcc compiler on Java platform which can be run on Windows.))

(Obviously I know in terms of file and function scope from this question)

Edit: OK give me an answer on any micro controller / processor environment.

like image 434
Manoj Doubts Avatar asked Nov 27 '08 07:11

Manoj Doubts


2 Answers

There is no difference for the space, they take the same amount.

But there is a speed difference: static is faster.

Of course the memory access to the variable is for global and static the same. But the compiler can optimize when you have static. When it compiles a module it knows that no function call to a function outside the module can change a static variable. So it knows exactly what happens and can e.g. keep it in a register over function calls. When it is global and you call a function from a different module, the compiler can't know what it does. Hence he must assume that the function accesses the variable and changes it, resulting in a store and reload.

With gcc you can pass all .c sources at the same time, so it can then also see what happens in function calls to functions from different modules. To make it work you have to pass besides all .c files at once -combine and -fwhole-program. The -fwhole-program makes all globals static (not module static but compilation unit static, i.e. all the given .c files together). The -combine makes the intermodule analysis.

like image 60
flolo Avatar answered Sep 21 '22 12:09

flolo


Space consumption: basically no difference. The only time there'd be a space issue is if you manage to get the same chunk of static data hidden in N object files, then you get a multiplication factor of N where you might have just 1 copy if it was a single global piece of data. However, that's a mis-design issue. Information hiding is good - unless the information should not be hidden.

Access speed: no difference.

like image 41
Jonathan Leffler Avatar answered Sep 21 '22 12:09

Jonathan Leffler