More on C++ stack arrays
David Nadlinger
code at klickverbot.at
Sun Oct 20 12:15:19 PDT 2013
On Sunday, 20 October 2013 at 18:42:06 UTC, Walter Bright wrote:
> If your optimizing compiler is that good, it can optimize "new
> T[n]" to be on the stack as well.
Just a side note: LDC actually does this if it can prove
statically that the size is bounded. Unfortunately, the range
detection is rather conservative (unless your allocation size
turns out to be a constant due to inlining, LLVM is unlikely to
get it).
One idea that might be interesting to think about is to insert a
run-time check for the size if an allocation is known not to be
escaped, but the size is not yet determined. As a GC allocation
is very expensive anyway, this probably wouldn't even be much of
a pessimization in the general case.
> I'm not particularly enamored with the compiler inserting
> silent copying to the heap - D programmers tend to not like
> such things.
Well, this is exactly what happens with closures, so one could
argue that there is precedent. In general, I agree with you,
though.
> I use this technique frequently. Allocating a few extra bytes
> on the stack generally costs nothing unless you're in a
> recursive function. Of course, if you're in a recursive
> function, stack allocated dynamic arrays can have unpredictable
> stack overflow issues.
I also find this pattern to be very useful. The LLVM support
libraries even package it up into a nice llvm::SmallVector<T, n>
template that allocates space for n elements inside the object,
falling back to heap allocation only if that threshold has been
exceeded (a tunable small string optimization, if you want).
David
More information about the Digitalmars-d
mailing list