Reputation: 953
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.
Upvotes: 16
Views: 5563
Reputation: 11
const int c =1;
int d = 1;
unsigned int e = 0;
start = std::chrono::steady_clock::now();
for (int i = 100000000; i--;) {
e += c;
e -= c;
e += c;
e -= c;
e += c;
e -= c;
e += c;
e -= c;
}
end = std::chrono::steady_clock::now();
time2 = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
cout << time2.count() << endl;
e = 0;
start = std::chrono::steady_clock::now();
for (int i = 100000000; i--;) {
e += d;
e -= d;
e += d;
e -= d;
e += d;
e -= d;
e += d;
e -= d;
}
end = std::chrono::steady_clock::now();
time2 = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
cout << time2.count() << endl;
Try this with the chrono libery and you will see that the code with const is faster. Const can make your code faster, but not everytime --> check this Fast Code with const ?
My Output of the Code above is -->
0.36604 //With const
0.416612
Upvotes: 0
Reputation: 681
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.
Upvotes: 6
Reputation: 69988
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.
Upvotes: 18