Global variables are slower?

Jeffrey A Law
Fri Feb 11 14:31:00 GMT 2000

  In message < 2473C7ACA21ED211854F08002BB768C40551D060@OZ >you write:
 > Somebody told me that accessing a global variable requires an extra
  > instruction, and thus, global variables are slower than local variables.
Sometimes many instructions -- it depends on the architecture.

  > Is this true for gcc generated code? I'm surprised if it is because I
  > understood from my knowledge of C that there was no performance difference
  > between local and global variables.
It's true for just about every compiler in the world.

Basically it it a lot easier for a compiler to prove certain optimization
are safe for automatic variables.


int a;

foo ()
  a = 5;
  blah ()
  a = 6;

You have to know what happens inside blah to know if it is safe to remove the
assignment to "a" before the call to blah.  Now consider

  int a;

  a = 5;
  blah ();
  a = 6;

The compiler can easily prove the first assignment to "a" is dead and remove

  > Can it be optimized out, at least for repeated accesses, if it is true?
Some of the overhead can be eliminted, but in general using globals is
going to be more expensive than using locals.  No way around it.

More information about the Gcc mailing list