On 2/15/2014 6:06 PM, Robin wrote:

Matrix is still a class but I changed it to a final class preventing
matrix methods to be virtual. Dimension is now a final struct (don't
know if 'final' is affecting structs in any way tough ...). This mainly
gave the multiplication a huge performance boost.


Like in other languages, "final" means "cannot inherit from this". Since structs, by definition, don't support inheritance anyway, "final" isn't really applicable - they're inherently "final" no matter what.

When converting the Matrix to a struct from class the multiplication
even lowered from ~4.3 seconds to about 3.6 seconds. However, I am
currently not sure if I want matrices to be structs (value types).


They really should be structs. There's basically no benefit to making them classes. Classes are for when you need inheritance and don't need performance. Java, from what I understand, does a reasonable job compensating for the inherent inefficiency of classes by going to great lengths to have absolute top-of-the-line class-oriented optimizations and GC and strip out all the class underpinnings when possible (AIUI). But D is much more like C# with "class vs struct" being an explicit thing.

Keep in mind too, the data inside dynamic arrays is already by reference. Arrays in D are basically like this:

struct Array(T)
{
    size_t length;
    T* ptr;
}

So even when your matrix is a struct, the actual values inside the matrix are still by reference (because it's through that pointer). So you're still not actually copying the data inside the matrix as you pass it around. You're only copying the dimension, length and pointer. And those are copied via a straight memcopy, not a "one field at a time" as I've heard C++ does (though I could be wrong, it's been forever since I did much C++).

And if you need to pass a struct by reference, there's always still "ref". Class really just isn't the right thing for a matrix, especially if you're paying attention to performance.


I have also tried the LDC compiler. However, it gave me some strange
bugs. E.g. it didn't like the following line:

ref Matrix transpose() const {
     return new Matrix(this).transposeAssign();
}


Doing that without parens around the "new Matrix(this)" is a very new feature, so I'm not entirely surprised LDC doesn't have it yet. Like Stanislav said, you can just add parens for now.


Reply via email to