Initializing a fixed sized array
finalpatch
fengli at gmail.com
Fri May 31 23:16:47 PDT 2013
This form is nice:
int[3] x = [1,2,3];
But it is horribly inefficient because it
1. allocates a dynamic array from the GC
2. writes 1,2,3 to the dynamic array
3. copies the 1,2,3 back to the static array
Or one can write:
int[3] x;
x[0] = 1;
x[1] = 2;
x[2] = 3;
That is a lot of typing, but also much more efficient than the
first version. But if I understand correctly, each element still
gets initialized to 0 before they got overwritten.
I would like to know whether we can have a way to initialize a
fixed array in D like what we can do in C++. In C++ if i write
int x[3] = {1, 2, 3}; then it's done in the most optimal way,
that is, simply assigning 1,2,3 to the 3 elements. no allocation,
no zero fill, no excessive copy. Better, if we write const static
int x[3] = {1,2,3}; then the array will be put in the read only
segment of the executable and result in zero runtime overhead.
However in D, static immutable int[3] x = [1,2,3]; still
allocates and copies. I wonder can we have some sort of array
initialization mechanism in D that is both nice and efficient?
More information about the Digitalmars-d
mailing list