, 2 min read
Consider using constexpr static function variables for performance in C++
3 thoughts on “Consider using constexpr static function variables for performance in C++”
, 2 min read
3 thoughts on “Consider using constexpr static function variables for performance in C++”
Hi!
I wonder if the benchmark between std::string and std::string_view is 100% fair.
Your functions that return std::string need to explicitly copy the grabbed string. If you make your “static const std::string” version return by reference, it really makes it as fast as the “static std::string_view” version.
About code bloat, I fully agree that the constexpr version is better.
Anyway, thanks for sharing!
I agree that the performance (in terms of speed) is sometimes (but not always) identical.
The reason why static and constexpr perform similar is that, most likely, the compiler will detect that the array is a constant expression (even if not specified), and remove it. This can be observed with your example-code in Godbolt. This is true for most code – a lot of the time, an optimizing compiler can do the same work regardless of whether a function is marked constexpr or not (as long as it can see the definition).
constexpr is mainly used to enforce this, even in a debug-build (aside from all the other uses where non-constexpr function cannot be used to). constexpr also forced the functions definition to be visible when used.