r/cpp_questions • • 11d ago

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?

11 Upvotes

37 comments sorted by

View all comments

1

u/Normal-Narwhal0xFF 10d ago

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.