0

I have multiple threads that instantiate the same class. I have NO concurrency problem. My question is performance-wise.

I have realized that accessing global variables sometime make a notable difference in performance. Why is that? ans what is the best practice? Should I copy the global variables to some member variables? Should I avoid global variables even if they do not make concurrency problems?

Computer_guy
  • 807
  • 2
  • 11
  • 19
  • Your question lacks specifics. What kind of performance issues are you seeing with global variables? How are you determining that the performance is notably different? – Santanu C Mar 10 '14 at 02:39
  • If anything, accessing global variables should be a bit *faster* than accessing members of objects (less indirection). If *measurements* show relevant differences, go right ahead. But keep a eye on the development cost the resulting obfuscation has. – vonbrand Mar 10 '14 at 02:40
  • Well, if access to your global variables is (implicitly) serialized (using critical sections or other similar techniques), then, yes, such access could be slower. But usual C++ policy demands that such decisions (whether to use mutexes or not are left for an application programmer) – user3159253 Mar 10 '14 at 02:51
  • No idea how your code is but there maybe a lot of locks or mutex around for different threads to access the same variables? In that case, that's the problem. It is also possible that global variables are taking up too much storage thereby slowing down the system. –  Mar 10 '14 at 04:39
  • As one can see, there are different answers. It is not obvious which approach is better. The reason lock issues should not be mixed with the question is that there would be a lock anyway. Only one thread updates and all other reads. My question is whether it is better to just read global values or copy them back to the member variable every time? – Computer_guy Mar 10 '14 at 11:06

0 Answers0