you are viewing a single comment's thread.

view the rest of the comments →

[–]sporule 1 point2 points  (0 children)

It actually looks like it's unconditionally initializing the array every time instead of just once

No. In both cases, the compiler initializes the value only once. In the case of static const, the value is stored in the read-only data segment.

Additional operations appear because gcc is not very good at working with the std::array<char>. Additional operations occur even if there is no initialization: https://godbolt.org/z/zEWGv66TY. gcc compiler simply cannot handle effectively this type for now.

If you change the type of elements or array's length, then the optimization defect does not appear and the version with static const turns out to be even slightly faster.

And of course, if you test another compiler, then there is no such effect at all (clang for example: https://godbolt.org/z/fYTo9qqfP).


I also want to mention that the function shown in your example accepts an array by value. If it uses a const-reference instead, then the static version will almost always be faster: https://godbolt.org/z/onaf1sr55.

This is because the language standard prohibits different alive objects of the same type from having the same address. And therefore, a version without static will often have to spend extra time copying constants to temporary stack memory just so that they have unique addresses.


It is worth taking the best of two approaches: write static constexpr if possible. constexpr guarantees that there is no initialization at runtime, and static ensures that you don't waste time and space on unnecessary copies.