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

Frank picture Frank · May 25, 2012 · Viewed 12.4k times · Source

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?

Answer

Alok Save picture Alok Save · May 25, 2012

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.