You can see of this as a small DEP :-)

Small variable-length arrays allocated on the stack can be somewhat useful in 
D. They avoid most usages of alloca() and are a bit safer than alloca() because 
no pointer casting is needed.

alloca() gives some performance improvement compared to normal dynamic arrays 
if the array is small and the function (here bar()) is called many times (I 
have experimentally seen this in the Levenshtein distance function, that needs 
to allocate a temporary buffer. If the length of the two input strings is small 
I use a fixed-sized array as buffer, this improves performance some in code 
that needs to compute this distance over many small strings. I think a 
variable-length array is a bit better here. In this situation often Tango 
adopts the strategy of adding an extra function argument that allows to give a 
preallocated buffer to a function).

The syntax that can be used for such arrays is nothing strange, it's the same 
as fixed-sized arrays, but the length is a run-time variable:

void foo(int[] b) {} // OK
// void foo(int[100] b) {} // Wrong

void bar(int n) {
  int[n] a; // stack-allocated, variable-size
  foo(a);
}

When you give one of such variable-length arrays to another function like 
foo(), it must always become a dynamic array, because the length is not 
generally unknown at compile time.

An alternative syntax that I don't like (too much long, and it doesn't allow to 
add =void):

void bar(int n) {
  scope int[] a = new int[n]; // stack-allocated
  foo(a);
}

The advantage of this scope int[] a =... syntax is that it's quite easy to see 
that it's a stack allocation, but I think this is not important.

Bye,
bearophile

Reply via email to