Considerations

If a global variable can be replaced as a global constant, then it should always be done. The reason for doing that is more than performance alone. Constants have the nice property of guaranteeing that their values are unchanged throughout the application life cycle. In general, the fewer global state changes, the more robust the program. Mutating states is traditionally a source of hard-to-find bugs.

At times, we may get into a situation that we cannot avoid using global variables. That's too bad. However, before we feel sad about that, we could also check whether the system performance is materially affected or not.

In the preceding example of adding two numbers, accessing the global variable carries a relatively large cost because the actual operation is so simple and efficient. Hence, more work is done in terms of getting access to the global variable. On the other hand, if we have a more complex function that takes much longer, say, 500 nanoseconds, then the extra 25 nanosecond overhead becomes much less significant. In that case, we may as well ignore the issue as the overhead becomes immaterial.

Finally, we should always watch out when too many global variables are used. The problem multiplies when more global variables are used. How many are too many? It really depends on your situation, but it does not hurt to think about the application design and ask yourself whether the application is designed properly.

In the next section, we will discuss a pattern that helps to improve system performance just by laying out data differently in memory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.180.76