Getting the const-correctness of Object sorted once and for all

Jonathan M Davis jmdavisProg at gmx.com
Sun May 13 22:48:52 PDT 2012


On Monday, May 14, 2012 07:34:44 Alex Rønne Petersen wrote:
> On 14-05-2012 06:18, Jonathan M Davis wrote:
> > On Monday, May 14, 2012 05:47:54 Alex Rønne Petersen wrote:
> >> It's kinda funny that something which on dlang.org's FAQ is described as
> >> a compiler optimization hint (http://dlang.org/const-faq.html#const)
> >> isn't useful at all for this purpose...
> > 
> > Oh, it's definitely useful for optimizations. It just doesn't work with a
> > couple of idioms that some programmers like to use in order to optimize
> > their code.
> > 
> > - Jonathan M Davis
> 
> I have yet to see any compiler make sensible use of the information
> provided by both C++'s const and D's const.
> 
> const in particular is completely useless to an optimizer because it
> does not give it any information that it can use for anything. The kind
> of information that an optimization pass, in general, wants to see is
> whether something is guaranteed to *never* change. const does not
> provide this information. const simply guarantees that the code working
> on the const data cannot alter it (but at the same time allows *other*
> code to alter it), which, as said, is useless to the optimizer.

Thanks to the fact that everything is thread-local normally, optimizations 
_can_ be made with const within chunks of code that can guarantee that no 
other reference of the same type (and therefore possibly to the same data) is 
used. How often such optimizations actually occur, I don't know.

In addition, it's possible (but not currently implemented) to have functions 
whose parameters are all const or implicitly convertible to const be strongly 
pure if they're passed immutable data (or data which is implicitly convertible 
to immutable). So, optimizations which we're not currently getting are 
definitely possible with just const.

It's definitely true that immutable provides more potential optimizations than 
const does, but const _does_ provide the opportunity for additional 
optimizations, and in cases where you're dealing with a value type, both const 
and immutable (they being more or less equivalent in such a case) allow for 
optimizations which C++ wouldn't, because the compiler not only doesn't have 
to worry about other references to the same data, but it knows that the data 
will never change from _any_ reference.

Regardless, it wouldn't surprise me in the least if the compiler could be 
doing additional optimizations for both const and immutable which it doesn't 
currently do.

- Jonathan M Davis


More information about the Digitalmars-d mailing list