Difference between revisions of "Dense multidimensional arrays"
(first draft) |
(→Dense dynamic arrays: oops) |
||
Line 49: | Line 49: | ||
enum columns = 100; | enum columns = 100; | ||
int rows = 100; | int rows = 100; | ||
− | double[ | + | double[columns][] gridInfo = new double[columns][](rows); |
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 18:42, 5 February 2013
There are several ways of declaring multidimensional arrays in D.
Jagged arrays
The simplest way is to use an array of arrays:
int[][] matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
assert(matrix[0][0] == 1);
assert(matrix[1][1] == 5);
This creates a so-called jagged array, because each element of the outer array can have different lengths:
int[][] matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6, 7, 8 ], // this is valid
[ 9, 10, 11 ]
];
However, this approach is not so memory-efficient, because the outer array is a separate block of memory containing references to the inner arrays, and the inner arrays are individually allocated. Array lookups also require multiple indirections, so there is a slight performance hit.
Static arrays
D recognizes the inefficiency of jagged arrays, so when all the dimensions of the array are known at compile-time, the array is automatically implemented as a dense array: the elements are packed together into a single memory block, and array access requires only a single indexed lookup:
// This is a dense array
int[3][3] matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
];
Dense arrays are fast and memory-efficient. But it requires that all array dimensions be known at compile-time, that is, it must be a static array. But what about dynamic arrays?
Dense dynamic arrays
There is a way to make multidimensional dynamic arrays dense, if only the last dimension needs to be variable:
enum columns = 100;
int rows = 100;
double[columns][] gridInfo = new double[columns][](rows);
This creates a multidimensional dynamic array with dense storage: all the array elements are contiguous in memory.
Credits
The idiom for creating dense multidimensional dynamic arrays was first posted to the D newsgroup by monarch_dodra.