Passing as const and by reference – Worth it?

Possible Duplicate:
How to pass objects to functions in C++?

In my game I make excessive use of mathematical vectors and operator overloading of them.

class Vector
{
   float x, y;
};

That’s basically all about my Vector class (methods excluded).

I am not an expert in C++ and I’ve seen and read about passing as const and passing by reference.

So, where are the performance differences in the below code example?

Float RandomCalculation( Vector a, Vector b )
{
    return a.x * b.x / b.x - a.x * RANDOM_CONSTANT;
}

// versus..

Float RandomCalculation( Vector& a, Vector& b )
{
    return a.x * b.x / b.x - a.x * RANDOM_CONSTANT;
}

// versus..

Float RandomCalculation( const Vector& a, const Vector& b )
{
    return a.x * b.x / b.x - a.x * RANDOM_CONSTANT;
}
  • Which of the three should I use, and why?
  • What advantages for the optimization process of the compiler does each of the options have?
  • When and where do I have to be especially careful?

Leave a Comment