Vectors and matrices in D
Bill Baxter
dnewsgroup at billbaxter.com
Thu Mar 15 11:21:37 PDT 2007
Andreas Zwinkau wrote:
>> I started implementing a little raytracer in D (raytracing is addictive, yeah ;)), and faced problems with vector/matrix math :(
>
> Me too :)
> I wanted to learn D and to write a raytracer for some time. Currently i have some time to do so. I got a little sidetracked into D templates by the vector implementation.
>
> Every implementation (Artyom, helix, some C++ raytracers) i've seen so far uses a struct for the vectors. Why? Performance? Does Bill Baxter hint at this?
> http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=46958
>
> I wrote a generic vector class. Maybe someone would like to comment on that? I it's just addition and subtraction so far, but the pattern is clear. Here comes my code:
>
I think the reason people use structs for Vector types is because
structs are for Plain Old Data, and Vectors are Plain Old Data. Mainly
the differences that they're constructed on the stack by default which
is generally what you want with something like a Vector (for 4-vectors
and lower at least). Other things also make them more struct like --
you want A = B to make a copy of B, not make a second reference to the
same B. You don't need to be able to subclass them.
The main problem is that passing big structs by value as parameters is
kind of slow. And it's something you want a lot. In C++ you'd use
const& Vector for the argument types, but in D there's no equivalent.
The good thing about using classes is that they're passed by reference
by default. But that's about the only good thing about them in this
context.
Allocations on the heap can be slow. Using 'scope' can get you around
that, but then you'll be using "scope Vector this", "scope Vector that"
all the time and it will get tiresome.
Anyway, if you're coming from Java then doing a heap allocation for
every vector may not seem like a big deal. But Java's allocations of
small objects are pretty heavily optimized from what I've heard. D
isn't really there.
Sorry if this is incoherent... I probably should have gone to be an hour
ago.
--bb
More information about the Digitalmars-d-learn
mailing list