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

后端 未结 5 1202
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-19 04:45

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 quali

相关标签:
5条回答
  • 2020-12-19 05:17

    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.

    0 讨论(0)
  • 2020-12-19 05:18

    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.

    0 讨论(0)
  • 2020-12-19 05:21

    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.

    0 讨论(0)
  • 2020-12-19 05:22

    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.)

    0 讨论(0)
  • 2020-12-19 05:25

    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.

    0 讨论(0)
提交回复
热议问题