Search code examples
c++performanceconstantsstateless

When working with stateless objects, is there still a performance benefit to marking them const?


Among other things, one reason for liberal use of const that I've seen is that, by ensuring that the value won't change, the compiler can more effectively optimize the resulting code. This seems reasonable (but I've also heard that the benefits of this are somewhat minimal).

In any case, would be same be true when working with stateless classes / objects? Could you reasonably expect even a minor speedup from marking stateless objects const, or are today's compilers good enough to recognize statelessness, and optimize for it regardless of whether its marked const or not?

Feel free to answer either in terms of specific compilers, or compilers in general.


Solution

  • A "stateless" object must be one with no member variables. A const method simply means that the implicit this pointer is const. But if you have no member variables, this is only useful to call member functions, and its constness just determines which overload will be called (presumably you'd not overload member functions on const when there is no state to mutate). So we should not expect (but might still discover!) any optimization difference when there is no state to modify, and when all the member functions called through this (if it's even a polymorphic class) will be const anyway.

    Of course, the most important thing to consider in optimization is your specific use case, with your specific compiler, on your specific platform. Only then will you know for sure if any of this matters.