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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access