Passing array as const slows down code?
Jonathan M Davis
jmdavisProg at gmx.com
Sat Apr 28 15:37:32 PDT 2012
On Saturday, April 28, 2012 13:17:36 Joseph Rushton Wakeling wrote:
> On 27/04/12 20:26, Steven Schveighoffer wrote:
> > No, it can't. There can easily be another non-const reference to the same
> > data. 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.
> >
> > Real optimization benefits come into play when immutable is there.
>
> Question on the const/immutable distinction. Given that my function has
> inputs of (size_t, size_t, Rating[]), how come the size_t's can be made
> immutable, but the Rating[] can only be made const/const ref?
>
> Is it because the size_t's can't conceivably be changed from outside while
> the function is running, whereas the values in the array in principle can
> be?
size_t is a value type. Arrays are reference types. So, when you pass a
size_t, you get a copy, but when you pass an array, you get a slice of the
array. You could make that slice const, but you can't make something
immutable, because immutable stuff must _always_ be immutable. If you want an
immutable array (or array of immutable elements), you must make a copy. If you
call idup on an array, you'll get a copy of that array where each of its
elements are immutable.
And yes, because size_t is copied, it can't be changed from the outside,
whereas because Rating[] is only sliced, it can be. const protects against it
being altered within the function (for both of them), but doesn't protect the
original array from being modified. immutable, on the other hand, is _always_
immutable and can never be mutated. But because of that, you can't convert
something to immutable without making a copy (which happens automatically with
value types but must be done explicitly with reference types).
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list