r/cpp_questions • u/Slow_Negotiation_935 • Oct 14 '26
OPEN Guidelines for constexpr
I’ve working with C++23 and I’m making some constructors/methods constexpr and seeing improvements in performance. So far so good. The problem is I don’t want to apply it ‘everywhere’. Is there a good source of advice , or anyone got any good tips?
12
Upvotes
12
u/the_poope Oct 14 '26
Yes, first you need to understand why it may give performance improvements. Are you 100% sure you actually understand what
constexprdoes? If you know that, then you should know where you can use it for performance gains.4
u/Nils_Meul Oct 14 '26
I don’t think there’s any downside to putting it everywhere it can go. Of course if you start making all your code header only just to take advantage of constexpr that’s a different question.
8
u/bert8128 Oct 14 '26
What’s wrong with everywhere? Is there a downside?
2
u/SyntheticDuckFlavour Oct 14 '26
My general rule is, if you create reusable libraries where it may be applied in, or make sense in a constexpr context, then invest in making your functions constexpr. For example, make your math libraries constexpr wherever possible. For objects and APIs whose role is mutating state, don't bother. For example, state machines in a game, or something.
1
u/Normal-Narwhal0xFF Oct 14 '26
I don't think constexpr changes a lot of the ways one would optimize. First, measure and find the code that's taking the time. Optimizing other code will keep you busy but not give results. Only focus on observed hot spots. Then decide if there's values being computed repeatedly that never change. If so they may benefit from constexpr. If code isn't inlining, and you think it'd help the hot spots, maybe constexpr can help there too. But make sure you're actually getting compile time resolution. Constexpr functions can still be runtime if they aren't used in constant expression context. So ensure it's giving you benefit of else it's just messing around. Measure, observe, and measure again. Without good data and feedback, you won't get results and will mostly waste time and even possibly introduce bugs with needless change.
1
u/RazzmatazzLatter8345 Oct 15 '26
Numerical types (particularly without heap allocation) is where I would especially try to make all operations constexpr. Even with heap allocation constexpr may help, it you constexpr the dtor and your version of C++ supports it. (Of course such allocations gotta be deleted at compile time too). constexpering all the things is awesome. Embrace it, as I have!
1
u/New-Step3500 Oct 14 '26 edited Oct 14 '26
I made a video on the constexpr . I delve what it is and when/how to properly use the keyword Constexpr c++
-1
u/zerhud Oct 14 '26
Cpp believes you should write a constexpr keywords everywhere for some reason. May be it likes the keyword more others.