Search code examples
c++performanceconstants

Does declaring C++ variables const help or hurt performance?


I understand the behavior of const-qualified data types. I am curious, though, if there is any performance gain or loss from over- or under-zealousness of qualifying variables as const. I am thinking particularly of variables declared and used exclusively within an isolated code block. For example, something like:

const qreal padding = CalculatePadding();
const QSizeF page_size = CalculatePagePreviewSize(padding);
const QRectF content_rect = CalculatePagePreviewContentRect(page_size);
const QList<QRectF> pages = renderer.BuildPrintPages(printer_, map_scene_);
const QFont page_number_font = CalculatePageNumberFont();
const QFontMetrics metrics(page_number_font);

Suppose I only need const-qualified methods on all of these (and more.) Is there any performance gain in declaring them all const? Or, conversely, does this actually hurt performance?

I am curious for both run-time performance (I am guessing this makes no difference as the const is exclusively a compile-time check--can someone confirm?) and compile-time performance. I do not have enough experience with c++ to have a feel for this, and am wondering if I should err on the side of over- or under-applying const when all other things (maintainability, etc.) are equal.


Solution

  • const is mainly a compile-time thing, however, declaring something as const sometimes allows for certain optimizations. If the code in question isn't a performance bottleneck, I wouldn't worry about it and just use const as intended: to produce clearer code and prevent yourself from doing stupid things.