Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

speed of accessing const variables in c/c++

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.

like image 454
Theemathas Chirananthavat Avatar asked Nov 29 '11 06:11

Theemathas Chirananthavat


People also ask

Is const faster in C?

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.

Are const variables faster?

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.

What is faster than const?

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.

Do constants use less memory?

No a constant uses the exact same memory. The only difference is that you can't change your constant after it's initialized.


2 Answers

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.

like image 142
iammilind Avatar answered Sep 28 '22 17:09

iammilind


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.

like image 25
Hucker Avatar answered Sep 28 '22 17:09

Hucker