On 2/14/2014 11:00 AM, Robin wrote:

class Matrix(T = double) {
     private T[] data;
     private Dimension dim;
}


A matrix is just plain-old-data, so use a struct, you don't need a class.

A struct will be much more lightweight: A struct doesn't normally involve memory allocations like a class does, and you'll get better data locality and less indirection, even compared to a final class.


I am using opIndex and opIndexAssign in order to access and assign the
matrix values:

T opIndex(size_t row, size_t col) const {
     immutable size_t i = this.dim.offset(row, col);
     if (i >= this.dim.size) {
         // TODO - have to learn exception handling in D first. :P
     }
     return this.data[i];
}

No need for the bounds check. D already does bounds checks automatically (unless you compile with -noboundscheck, but the whole *point* of that flag is to disable bounds checks.)

But that said, I don't know whether the compiler might already be optimizing out your bounds check anyway. So try it and profile, see what happens.


Another nice thing to know would be if it is possible to initialize an
array before it is default initialized with T.init where T is the type
of the array's fields. In C++ e.g. there is no default initialization
which is nice if you have to initialize every single field anyway. E.g.
in a Matrix.random() method which creates a matrix with random values.
There it is unnecessary that the (sometimes huge) array is completely
initialized with the type's init value.

You can opt-out of the default initialization with a void initializer: http://dlang.org/declaration.html#VoidInitializer

Although to be honest I forget how to do that for arrays, and the functions other people already suggested for creating/initing your array probably already do that anyway.

Reply via email to