Why people dislike global variables so much while I find them so convenient?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Tue Jan 25 12:07:31 UTC 2022


On Tuesday, 25 January 2022 at 11:37:54 UTC, rempas wrote:
> On Tuesday, 25 January 2022 at 10:22:17 UTC, Ola Fosheim 
> Grøstad wrote:
>> Harder to debug
>
> How?
>
>> Harder to reason about as your program grows

Because the program is larger, there are more locations that 
could mutate the global state. ("reason" ≈ "prove correct")


>> Harder to scale your program to higher degree of concurrency
>
> Why? What's the difference between having a variable in a

1. globals are singletons, it becomes difficult to have multiple 
instance if you later regret having only one instance.

2. because you need to use locking correctly to prevent multiple 
threads from mutating the state at once and then you have to 
prove that your locking strategy is does not lead to starvation 
or deadlocks.


> I mean, if you keep them local to an object file that they lose 
> their bigger advantage. How many functions will be in this file 
> compared to the whole project? So we don't win much.

I don't understand what you are trying to say here.

The global variable should be local to the object file. The 
accessor functions can be globally accessible.


> Yeah but in that case, I will have to create an object and use 
> pointers. And also use a pointer for this object and have to 
> dereference it every time. So yeah, the runtime performance 
> will not be happy about that...

Passing one pointer isn't particularly expensive. What (non-TLS) 
globals save you on some CPUs are registers and time spent on 
allocation.

For instance,  using globals can make sense in embedded 
programming on tiny CPUs with very little RAM.


>> If you use globals, make sure you either mark them 
>> appropriately so that you don't get thread local globals.
>
> How can I do that?

https://dlang.org/spec/attribute.html#gshared





More information about the Digitalmars-d mailing list