Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use const for local variables for better code optimization?

I often use const for local variables that are not being modified, like this:

const float height = person.getHeight(); 

I think it can make the compiled code potentially faster, allowing the compiler to do some more optimization. Or am I wrong, and compilers can figure out by themselves that the local variable is never modified?

like image 550
Frank Avatar asked May 25 '12 02:05

Frank


People also ask

Does using const improve performance?

const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic , meaning the compiler has to respect changes made by other threads.

Does const make code faster?

No, const does not help the compiler make faster code. Const is for const-correctness, not optimizations.

Are const variables faster?

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.

Should I always use const reference?

When writing a C++ function which has args that are being passed to it, from my understanding const should always be used if you can guarantuee that the object will not be changed or a const pointer if the pointer won't be changed.


2 Answers

Or am I wrong, and compilers can figure out by themselves that the local variable is never modified?

Most of the compilers are smart enough to figure this out themselves.
You should rather use const for ensuring const-correctness and not for micro-optimization.
const correctness lets compiler help you guard against making honest mistakes, so you should use const wherever possible but for maintainability reasons & preventing yourself from doing stupid mistakes.

It is good to understand the performance implications of code we write but excessive micro-optimization should be avoided. With regards to performance one should follow the,

80-20 Rule:

Identify the 20% of your code which uses 80% of your resources, through profiling on representative data sets and only then attempt to optimize those bottlenecks.

like image 200
Alok Save Avatar answered Oct 01 '22 12:10

Alok Save


This performance difference will almost certainly be negligible, however you should be using const whenever possible for code documentation reasons. Often times, compilers can figure this out for your anyway and make the optimizations automatically. const is really more about code readability and clarity than performance.

like image 31
Oleksi Avatar answered Oct 01 '22 11:10

Oleksi