I've been working on a class project for a few days now where I need to modify and improve a program given to us by the teacher. The program mostly relies on a struct Vector, defined as:
1 2 3 4 5 6 7
|
struct Vector
{
float x;
float y;
float z;
float w;
}
|
He asked us to replace this struct with a simple
float[4]
and alter all the functions accordingly. He suggested we change the functions, which had a general look of
(Vector) v = algAdd(v1,v2)
to
algAdd(v1,v2,&v)
, so that there was less time spent doing bit-wise copies to and fro. However, I saw that this could all be a lot tidier if I did it with a bit more C++, i.e., making
algAdd()
a member of
Vector
, thus changing it from
1 2 3 4 5
|
Vector algAdd( Vector v1, Vector v2 )
{
Vector v = {v1.x + v2.x, v1.y + v2.y, v1.z + v2.z, v1.w};
return v;
}
|
to a member-function of Vector, thus turning it into
1 2 3 4 5 6 7 8 9
|
void Vector::Add(Vector& v1, Vector& v2)
{
v[0] = v1.v[0]+v2.v[0];
v[1] = v1.v[1]+v2.v[1];
v[2] = v1.v[2]+v2.v[2];
v[3] = 1;
}
v.Add(v1,v2); //v = v1 + v2
|
I've done this to all the functions, changing them from functions that return a value to functions that immediately insert the values into the caller's variables.
However, when I compare the speed of my program vs. the one originally given by the teacher, mine is consistently slower. His version runs at approx. 3 seconds, while mine is approx. 3.25 seconds (in great part due to the answers to another question I put here today). It's not much, sure, but... mine should be faster, not slower. I've in fact altered every single function regarding this struct so that not a one returns a value. They all return
void
and simply inject the values into the caller.
So now I ask: is this just a mistake on my part? With the example above, should mine be faster (i.e. the mistake is somewhere else)? Am I misunderstanding something regarding member functions? Do they actually create temporary variables and then create bit-wise copies into the real variables? In short, does anyone know what it could be?