A slice can lose capacity simply by calling a function

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 3 18:06:34 PDT 2015


On Sunday, May 03, 2015 15:21:15 Andrew Godfrey via Digitalmars-d-learn wrote:
>
> > I really don't think that it's an issue in general, but if you
> > do want to
> > guarantee that nothing affects the capacity of your array, then
> > you're going
> > to need to either wrap all access to it
>
> I agree with everything Jonathan said in both threads EXCEPT that
> this is not an issue.
>
> The syntax "slice.capacity" gives the impression that 'capacity'
> is a property of the slice.
>
> Such lack of consistency is a SERIOUS issue for D, especially
> when it occurs in something as basic as an array.

I really don't see the problem. It's a natural side effect of how dynamic
arrays work in D. The only thing I can see that could be changed without
losing some of the capabilities that we currently have is if capacity were
explicitly a separate function - e.g. calcArrayCapacity - but I really don't
think that that would buy us much. You'd still have to understand how D's
dynamic arrays work to understand how the capacity for a dynamic array
works. And most code really doesn't care about the capacity of an array. If
you profile and find that appending to an array is a hot spot in your
program, then you dig in and use reserve or Appender or use something other
than a naked array, and you figure out what works best for your particular
use case, but for most code, it just works to use ~=. And if you're
concerned about reallocations even before profiling, then it's trivial to
just call reserve first or to use Appender. And unless you're doing
something like constantly slicing and appending to each slice (which I
expect to be a rare thing to do), you're really not going to run into
problems.

Sure, the semantics of D's dynamic arrays take some getting used to -
especially if you want to understand all of their ins and outs. But I really
don't see why it's a big problem. For the most part, D's dynamic arrays just
work.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list