声明C ++变量const帮助还是损害性能? [英] Does declaring C++ variables const help or hurt performance?
问题描述
我了解 const
- 资格类型的行为。我很好奇,如果有任何性能获得或损失从过热或缺乏热情的合格变量 const
。我特别想到在一个孤立的代码块中声明和使用的变量。例如:
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);
假设我只需要 const
在所有这些(和更多。)是否有任何性能获益,宣布他们 const
?
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?
我对运行时的性能感到好奇(我猜这没有什么区别,因为 const
只是编译时检查 - 有人可以确认吗?)和编译时性能。我没有足够的经验与c ++有这种感觉,我想知道如果我应该错误的过度或低于应用程序 const
当所有其他事情(维护性等)相等。
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
一个编译时事情,然而,声明一些 const
有时允许某些优化。如果有问题的代码不是性能瓶颈,我不担心它,只是使用 const
意图:产生更清晰的代码,防止自己做蠢事。
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.
这篇关于声明C ++变量const帮助还是损害性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!