Is accessing const
variables faster than non-const
variable? I'm wondering if it is worth using const
more as a step in optimizing a program.
Yes, const can (not guaranteed) help the compiler produce faster/more correct code. More so than not, they're just a modifier on data that you express to both the compiler and to other people that read your code that some data is not supposed to change. This helps the type system help you write more correct software.
Just like we saw for variables, there was no difference in performance for functions declared as const variables using the arrow syntax compared to those declared using the traditional function keyword syntax.
The advantage of #define is that it guarantees constness and therefore there will be no backing variable. Const Variables may or may not be substituted into the code, so #define might be faster in some situations.
No a constant uses the exact same memory. The only difference is that you can't change your constant after it's initialized.
If the value is a compile time constant (e.g. numbers, enum
, const
values, constexpr
sometimes in c++11 and so on), then yes they can be accessed faster compared to other variables. They can even be placed in the code segment.
However, it's not true for any const
:
const int x = 5; // can be faster
const int c = foo(); // normal non-modfiable variable, normal speed
From the example you can see that, all non-modifiable variables are not compile time constants.
The answer to your question is maybe.
As Bjorn pointed out this question can only be answered by careful benchmarking because there are too many architecture specific reasons why the answer could be yes or no.
Here is a StackOverflow reference on benchmarking:
If you are working on a project where speed matters then the only way to really know what the compiler is doing and how it impacts speed is to read the generated assembly and perform careful benchmarking. Theorizing about what the compiler could do isn't productive. If you are working on an embedded system an oscilloscope is a great way to time things, on machines with more resources a high resolution timer provided by the OS is useful.
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