Global Vs Local Variables

This is a discussion on Global Vs Local Variables within the C++ Programming forums, part of the General Programming Boards category; Is there any performance hit between their respective uses? If I were to use all global or all local, would ...

  1. #1
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001

    Global Vs Local Variables

    Is there any performance hit between their respective uses? If I were to use all global or all local, would it matter in any way (besides scope)?
    PHP and XML
    Let's talk about SAX

  2. #2
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    This is a global scope & local variable. Theres' nothing for you here.

    >Is there any performance hit

    I doubt it.

  3. #3
    PC Fixer-Upper Waldo2k2's Avatar
    Join Date
    May 2002
    Posts
    2,001
    ok, just curious

    my friend is taking c in college, his teacher has been touting global variables as "evil" in some way. Jus wondering if there was any merit to what she was spewing.
    PHP and XML
    Let's talk about SAX

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    Global variables can be a pain as every function in the module has the ability to change the value.....and this can be difficult to debug.

    They can be faster to use than local variables though, as locals are stored on the stack...but unless the speed is a real factor, you should look at local variables when you can

  5. #5
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    speed is a factor because locals are usually reallocated each time in. This is something you can live with though if you want to write clean code. Global is evil if you ever do multithreaded apps. You will constantly crash if you use globals across threads.
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  6. #6
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    Widespread use of global variables is bad programming, because it is not modular.

    >They can be faster to use than local variables though, as locals are stored on the stack

    I suspect you'd be hard-pushed to notice a difference in performance for most applications. Obviously depends on what your doing, but generally I would have thought it's a non-issue. However, I don't mean to contradict Fordy.

    >speed is a factor because locals are usually reallocated each time in

    May be it might worth writing a simple program to speed test the two?

  7. #7
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    I think for most fortran 90 compilers,
    variables are all static unless there're in
    a recursive function. Static variables or static globals are suppose to be faster since they use direct acess where as locals
    use indirect access.

  8. #8
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    Originally posted by Davros
    I suspect you'd be hard-pushed to notice a difference in performance for most applications. Obviously depends on what your doing, but generally I would have thought it's a non-issue. However, I don't mean to contradict Fordy.
    I dont do much game programming, but I notice a lot of code where variables are global....So when a function is called, instead of passing a parameter to the function (and thereby having to store a copy or a pointer to a variable on the stack) they all just refer to a global variable....so then for the call, there are no params to pass and the only thing stored on the stack is th return address of the calling function....and if you inline, you might even forego that!

    But game programming is a different kettle of fish from most situations....and even then, the difference might not be noticable......all depends on what you are doing I suppose....

  9. #9
    Shadow12345
    Guest
    Well I don't really have anything new to say about this topic, I mean yes if you could accurately meaure speed in terms of nanoseconds and compared the time it would take to process a function that uses local variables it would take longer to process than one referring to global variables. So there is a difference but nothing you would ever see. There are bigger things to wory about in most applications.

    In terms of game programming global variables are usually safe to use. The types of global variables are ones that usually do not change throughout the entire program, or they only change in one place in the entire program. Common global variables for games tend to be:
    device contexts, rendering contexts, window handles, instances of api specific variables including cameras, texture arrays, angles, you name it. The window handles are usually global because they need to be initialized and set up, but a single instance of a window may need to be referred to in order call messagebox functions to describe errors, print frame rates to the screen, release (delete) the contexts, setup pixel formats, etc, you can see how it is easier to just use global variables.

  10. #10
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    >I suspect you'd be hard-pushed to notice a difference in performance for most applications.

    Let me try it out. I'm curious now.
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

  11. #11
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    "easier" is a horrible way to look at it. In any large project, globals make things more complicated. speed is the only valid reason to keep globals today.
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  12. #12
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    OK. I have some results.

    Before I give them. Please someone explain to me extactly what you all mean by global & local. Give me a trivial example. I don't have the results you expect, so I want to avoid looking stupid.

  13. #13
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    I ran a similar test and came up with results that Davros would like. Local ran FASTER. I could explain it away by saying that it has everything to do with compiler optimizations but I don't care to. I believe global is evil regardless.
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  14. #14
    pronounced 'fib' FillYourBrain's Avatar
    Join Date
    Aug 2002
    Posts
    2,297
    here's what I ran in case anyone cares
    Code:
    #include <windows.h>
    #include <iostream>
    
    
    
    void Local()
         {
         char str[10000];
         str[0]++;
         }
    
    char g_str[10000];
    
    void Global()
         {
         g_str[0]++;
         }
    
                         
    int main(void)
         {
         unsigned long begin, end;
         int i;
    
         begin = ::GetTickCount();
         for(i = 0; i < 100000; i++)
              Local();
         end = ::GetTickCount();
         
         std::cout << "Local - " << begin-end << std::endl;
    
         begin = ::GetTickCount();
         for(i = 0; i < 100000; i++)
              Global();
         end = ::GetTickCount();
         std::cout << "Global - " << begin-end << std::endl;
         return 0;
         }
    "You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter

  15. #15
    Code Monkey Davros's Avatar
    Join Date
    Jun 2002
    Posts
    812
    I run my code using simple integers, over large loops, as below.

    I found local variables to be consistently five times faster than global variables.

    I also ran FYBs code (although I extended the loop). I expected the local function to be slower because he is declaring quite a large amount of mem on the stack (and pulling it off) on each call. However, both ran at roughly the same speed. Although I suspect if I were to increase the array size, the local will become slower.

    However, simple access to local variable seems to be faster. I'm guessing here, but does the CPU have somekind of fast cache which is being used for the stack?

    I also take Fordy's point about passing parameters to functions using global variables. However, this appears that it may be counter productive, unless you are passing large amounts of data (in which case you could use pointers). In any case, it must be a dreadful way to program a large application.


    Code:
    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
      double t1 = Now();
      eg = 0;
      for(int n = 0; n < 1000000000; n++)
      {
        eg++;
      }
      double t2 = Now();
      Label1->Caption = (t2 - t1) * 86400;
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::Button2Click(TObject *Sender)
    {
      double t1 = Now();
      sg = 0;
      for(int n = 0; n < 1000000000; n++)
      {
        sg++;
      }
      double t2 = Now();
      Label2->Caption = (t2 - t1) * 86400;
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::Button3Click(TObject *Sender)
    {
      double t1 = Now();
      int lv = 0;
    
      for(int n = 0; n < 1000000000; n++)
      {
        lv++;
      }
      double t2 = Now();
      Label3->Caption = (t2 - t1) * 86400;
    }
    //---------------------------------------------------------------------------
    where
    extern int eg;
    static int sg;

    and lv local to Button3Click
    OS: Windows XP
    Compilers: MinGW (Code::Blocks), BCB 5

    BigAngryDog.com

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Craps Program with Local Variables
    By tigrfire in forum C Programming
    Replies: 12
    Last Post: 11-09-2005, 08:01 AM
  2. local and global variables???
    By geo_c in forum C Programming
    Replies: 5
    Last Post: 08-23-2004, 03:02 PM
  3. Replies: 6
    Last Post: 01-02-2004, 12:01 PM
  4. Global variables.. how bad?
    By punkrockguy318 in forum C++ Programming
    Replies: 19
    Last Post: 11-30-2003, 09:53 PM
  5. global and local variables
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 10-02-2001, 01:17 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21