Variable-length stack allocated arrays

dsimcha dsimcha at yahoo.com
Mon Jan 11 06:17:58 PST 2010


== Quote from Andrei Alexandrescu (SeeWebsiteForEmail at erdani.org)'s article
> grauzone wrote:
> > bearophile wrote:
> >> void bar(int n) {
> >>   scope int[] a = new int[n]; // stack-allocated
> >>   foo(a);
> >> }
> >
> > Why are you making such proposals, when one of the core developers even
> > thought about removing normal "scope"? It's almost 100% guaranteed that
> > nobody will listen.
> >
> > I personally find it a good idea to find new ways to reduce producing
> > memory garbage. The D GC is slow and bad, so you'd better avoid it.
> >
> > Let's make this claim: it is impossible to write high performance
> > applications (that need to make use of dynamic memory allocation) in D
> > without resorting to "unsafe" techniques. That would include allocating
> > memory on the stack, or manually freeing memory.
> I write high-performance code in D without resorting to unsafe
> techniques. Much of my code allocates arrays only in the beginning and
> uses them throughout.

One thing I've always wondered about people who operate this way is, how do you do
it without violating tons of encapsulation?  For example, let's say you want foo()
to be a well-encapsulated free function:

int foo(int num) {
    int[] temp = new int[num];
    // Do stuff.
}

Now how do you draw a line of abstraction that reuses temp in a well-encapsulated
way, one that is invisible to the caller of foo()?

Since bugs that occur at higher levels of abstraction are often caused by poor
encapsulation and programs that are too hard to reason about, I'd rather have a
well-encapsulated "unsafe" speed hack than a poorly encapsulated "safe" one.



More information about the Digitalmars-d mailing list