Passing array as const slows down code?

Jonathan M Davis jmdavisProg at gmx.com
Fri Apr 27 12:17:57 PDT 2012


On Friday, April 27, 2012 14:26:52 Steven Schveighoffer wrote:
> On Fri, 27 Apr 2012 13:23:46 -0400, Jonathan M Davis <jmdavisProg at gmx.com>
> 
> wrote:
> > On Friday, April 27, 2012 11:18:26 Steven Schveighoffer wrote:
> >> const should not affect code generation *at all*, except for name
> >> mangling
> >> (const MyStruct is a different type from MyStruct), and generating an
> >> extra TypeInfo for const MyStruct and const MyStruct[]. Const is purely
> >> a
> >> compile-time concept.
> > 
> > Thanks to the fact that const is transitive and that it's illegal to
> > cast it
> > away to use mutation, const _can_ affect code optimizations, but I don't
> > know
> > exactly under what circumstances it does in the current compiler.
> 
> No, it can't. There can easily be another non-const reference to the same
> data.

Except that if the variable isn't shared, then in many cases, it doesn't 
matter that there can be another reference - particularly when combined with 
pure. So, the compiler definitely should be able to use const for optimizations 
in at least some cases. It wouldn't surprise me if it doesn't use it for that 
all that much right now though.

> Pure functions can make more assumptions, based on the types, but
> it would be a very complex determination in the type system to see if two
> parameters alias the same data.

Yes. But that doesn't matter in many cases thanks to D's thread-local by 
default. With shared, on the other hand, const becomes useless for 
optimizations for the very reason that you give. And yes, there _are_ cases 
where const can't be used for optimizations because other references are used 
which might refer to the same data, but particularly if no other references of 
the same type are used in a section of code, then the compiler should be able 
to determine that the object really hasn't changed thanks to const.

> Real optimization benefits come into play when immutable is there.

Definitely. immutable allows for much better optimizations than const does, but 
there _are_ cases where const allows for optimizations.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list