3

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.

Kevin
  • 1,870
  • 2
  • 20
  • 22

2 Answers2

1

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
1

are today's compilers good enough to recognize statelessness, and optimize for it regardless of whether its marked const or not?

There's nothing to optimise! You have no data access, so the object being const is 100% meaningless.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • My thought was that, stateless objects could have method calls inlined (or possibly even evaluated at compile time). – Kevin Nov 09 '14 at 19:40
  • @Kevin: They already will be where possible. Marking a member function of a class with no members `const` will make literally zero difference, because by definition you already have no accesses to data members within that function. – Lightness Races in Orbit Nov 09 '14 at 22:39