Do global variables mean faster code?

后端 未结 14 1889
情深已故
情深已故 2020-12-24 00:58

I read recently, in an article on game programming written in 1996, that using global variables is faster than passing parameters.

Was this ever true, and if so, is

相关标签:
14条回答
  • 2020-12-24 01:50

    What do you mean, "faster"?

    I know for a fact, that understanding a program with global variables takes me a whole lot more time than one without.

    If the extra time it takes the programmer(s) is less than the time gained by the users when they run the program with globals, then I'd say using global is faster.

    But consider that the program is going to be run by 10 people once a day for 2 years. And that it takes 2.84632 secs without globals and 2.84217 secs with globals (a 0.00415 sec increase). That's 727 seconds less of TOTAL runtime. Gaining 10 minutes of run time is not worth the introduction of a global as regards programmer time.

    0 讨论(0)
  • 2020-12-24 01:52

    Like everything else: yes and no. There is no one answer because it depends on context.

    Counterpoints:

    • Imagine programming on Itanium where you have hundreds of registers. You can put quite a few globals into those, which will be faster than the typical way globals are implemented in C (some static address (although they might just hardcode the globals into instructions if they are word length)). Even if the globals are in cache the whole time, registers may still be faster.

    • In Java, overuse of globals (statics) can decrease performance because of initialization locks that have to be done. If 10 classes want to access some static class, they all have to wait for that class to finish initializing its static fields, which can take anywhere form no time up to forever.

    In any case, global state is just bad practice, it raises code complexity. Well designed code is naturally fast enough 99.9% of the time. It seems like newer languages are removing global state all together. E removes global state because it violates their security model. Haskell removes state all together. The fact that Haskell exists and has implementations that outperform most other languages is proof enough for me that I will never use globals again.

    Also, in the near future, when we all have hundreds of cores, global state isn't really going to help much.

    0 讨论(0)
提交回复
热议问题