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.
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.
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.
Constants can make your program more readable. For example, you can declare: Const PI = 3.141592654. Then, within the body of your program, you can make calculations that have something to do with a circle. Constants can make your program more readable.
The most important reason is to avoid bugs. By marking something const , you allow the compiler to catch any attempts to change it. For example, imagine if some variable is passed by reference to a function that changes it. If you marked that variable const , the compiler will catch that.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With