Is it possible to gain performance in C++ by declaring a variable static
, const
or making it global
?
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.
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.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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With