Arrays, garbage collection
bearophile via Digitalmars-d
digitalmars-d at puremagic.com
Thu Jan 29 17:08:30 PST 2015
The D type inference for array literals is now more flexible:
void main() {
auto[$][$] m1 = [[1, 2], [3, 4], [5, 6]];
pragma(msg, typeof(m1)); // int[2][3]
const auto[string] aa1 = ["red": 1, "blue": 2];
pragma(msg, typeof(aa1)); // const(int)[string]
}
It helps avoid bugs like:
int[5] a = [1,2,4,5];
void main() {}
And it makes the usage of value arrays (fixed size arrays) more
handy. We need to minimize the work that the garbage collector
has to do. Value arrays help in this. So making value arrays more
handy and natural to use is good (regardless how the current
Phobos hates them).
- - - - - - - - -
What's missing is a handy and compiler-efficient syntax to create
value array literals. Some persons have proposed the "[]s" syntax:
void main() {
// Some imports here.
foo([[1, 2]s, [3, 4]]s);
auto t1 = tuple([1, 2]s, "red");
auto aa1 = ["key": [1, 2]s];
auto pairs = 10.iota.map!(i => [i, i + 10]s);
}
To do those same things without the []s syntax you have to write
longer code.
- - - - - - - - -
Another missing handy feature regards dynamic/associative arrays
(this syntax is currently accepted):
void main() {
scope int[] a = [1, 2];
scope int[int] aa = [1: 2];
}
A good management of memory ownership is needed to make "scope
dynamic/associative arrays" fully safe. They should be more
efficient for the GC because they can be deallocated safely when
the scope ends, without no need for the GC to track their usage
(if they contain references to objects that contain other
references, then the GC has to track and manage those other
references).
- - - - - - - - -
Sometimes I have suggested that it's useful to have in Phobos a
kind of variable-length value arrays that are handled in a
special way by the compiler when they are allocated in a stack
frame, usable in @nogc functions (so it's a hybrid Phobos/D
feature). This should give the advantages of C99 Variable Length
Arrays without most of their disadvantages and complexities (the
main disadvantage that's left is the risk of stack overflow.
Currently on Windows D doesn't give a nice error message when the
stack overflows, as it used to do).
- - - - - - - - -
With those features, with a good static management of memory
ownership, D can become safer and reduce the work for the GC. I
think only a limited percentage of arrays need to be fully
handled by the GC.
Bye,
bearophile
More information about the Digitalmars-d
mailing list