Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance gain from static, const and global variables [closed]

Tags:

c++

Is it possible to gain performance in C++ by declaring a variable static, const or making it global?

like image 746
We're All Mad Here Avatar asked Jan 09 '14 22:01

We're All Mad Here


2 Answers

You are very unlikely to outperform a function local variable of a built-in type with putting it somewhere else except: If the value of the variable can be computed at compile-time, making it a constexpr will be ideal.

  • Making the variable static may incur a small cost on every call of the function determining if the object was already initialized, especially with C++11 where the initialization is thread-safe. Even if it doesn't need a check, the stack is likely to be in cached memory while a static variable is not.
  • Making a variable global will increase the chances that it isn't in cached memory, i.e., there is a good chance that it will be slower (aside from adverse other potential like making it a good candidate to introduce data races).
  • Making a variable const may help if the compiler can compute the value as compile time.

If the variable has a non-trivial type things get more intersting because the initialization cost, e.g., of a std::vector<T> is non-trivial. I wouldn't expect a difference between making the objects static function local compared to global objects (i.e., I wouldn't make them global; there is no space for global objects anyway). However, making objects static introduces the potential that they may be shared between threads. If that is a concern the added locking and serialization probably defeats any potential savings and using allocators using stack-based memory is a better approach to improve the costs (assuming they are small enough to reasonably life on the stack).

like image 92
Dietmar Kühl Avatar answered Oct 21 '22 04:10

Dietmar Kühl


Performance depends on many factors, you can not assume that simply changing this details would really improve performance.

The best approach to improve performance is to understand the details of your implementation and apply a profiling tool to identify your real bottlenecks.

Most of the time people tend to early optimize code, employing to much effort and making code unreadable on parts that doesn't have much impact on the overall performance of the application.

Cheers

like image 25
prmottajr Avatar answered Oct 21 '22 03:10

prmottajr