8

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.

Dave Mateer
  • 17,608
  • 15
  • 96
  • 149

6 Answers6

27

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.

tdammers
  • 20,353
  • 1
  • 39
  • 56
4

In my (limited) experience, const CAN hurt the performance by quite a lot (surprise!) Namely, when working with container classes be careful what cont-ness does: for arrays it might simply force the compiler to create a copy of your container (e.g., an array) once a single element is accessed for reading only... This was a huge pain to locate in the code that I am working on.

yuriy
  • 49
  • 1
2

My understanding is that const can be used by the compiler to potentially optimize performance, but is no guarantee of such; there shouldn't be a performance downside, though. It could potentially affect runtime behavior (ie: the compiler could put const variables on read-only memory pages).

It should not have a significant impact on performance, but I'd error on using it more for ease of code maintenance. Just my opinion, though.

Nick
  • 6,808
  • 1
  • 22
  • 34
1

While the answer is technically "yes", the practical answer is NO. It's true that the compiler can, under certain circumstances, perform code optimizations by taking into account that a given value cannot change or that a method will not modify the owning object. However, these will be situational cases and so incredibly far down in the weeds of optimization that it would almost certainly be a mistake to take it into account up front.

Rakis
  • 7,779
  • 24
  • 25
0

const is just there to help you catch errors at compile time. However since there's this thing called the const_cast you can always change the constness of any variable so the compiler really can't get away with optimizing anything away. (You can also have fun with c-style casts to get rid of constness which could make optimizations invalid.)

miked
  • 3,458
  • 1
  • 22
  • 25
  • 1
    avoid `const_cast` at all times, and use it only when you have no choice (eg: you're working with an external lib you can't change the interface of, but know modifying a const object is "safe enough"). – rubenvb Oct 05 '10 at 19:52
  • 2
    This is not really true. If you defined a variable as const, you cannot cast that away *and* write to it. A compiler that caches a variable value based on the fact that the variable is const is alright. Any program that writes to a const variable has undefined behavior. – Johannes Schaub - litb Oct 05 '10 at 20:41
  • Johannes - first result from a google search on const and optimization: http://www.gotw.ca/gotw/081.htm - try it yourself, you can write to an unconstified variable – miked Oct 05 '10 at 21:27
  • 2
    The link you referred to is a different situation, where you get a constant reference to a possibly not constant object. Johannes refers to the situation where the original variable is declared as `const type name`, and modifying `name` there is undefined behavior. Consider for example, that a conforming compiler could decide to place that variable in ROM instead of regular memory, or in a read-only memory page. In both cases, trying to modify the variable could fail silently or crash the application. – David Rodríguez - dribeas Oct 05 '10 at 22:01
  • 2
    i.e. If you add const-ness to a non-const object by binding it to a constant reference, you cast away the const-ness and modify it, that is ok. But you cannot cast away the const-ness of an object that **is** const. – David Rodríguez - dribeas Oct 05 '10 at 22:03
0

Yes, const can improve performance if applied to the object itself.

Example:

int fmutable(void g(const int &)) {
    int x = 1;
    g(x);
    return x;  // mov rax, dword ptr [rsp + ...]
}

int fconst(void g(const int &)) {
    int const x = 1;
    g(x);
    return x;  // mov eax, 1
}

This happens because mutating a const object is illegal, so the compiler can assume you don't do that.

However, adding const to the target of a reference or pointer that was previously mutable doesn't improve performance, because casting away const and then mutating an object that wasn't originally const is legal, and the compiler cannot assume you don't do that.

user541686
  • 205,094
  • 128
  • 528
  • 886