Search code examples
c++language-agnostic

Should a class perform bounds checking when you are after performance


Say I have a triangle class, defined something like

class Triangle{
vertex3D vertexs[3];
public:
vertex* GetVertex(int vertexNumber);
}

now for most normal applications its fairly obvious that GetVertex should ensure that vertexNumber is a valid index before trying to return the vertex pointer. I would say that normally it can return NULL if vertexNumber is not valid, but that's not really what I am asking about.

In a game situation, checking if vertexNumber is valid all the time could take up a fair bit of time, it would be quicker for GetVertex to assume that only valid values will be passed in.

So would it be acceptable for triangle to basically throw caution to the wind in the name of a slight performance boost?

If I do go for a bounds checking in debug but not release, how can I automate this so that I don't have to edit the code? Some sort of compile time switch or something? would using #ifdef debug sort of stuff work? where can I find more about this?


Solution

  • You should definitely check the bounds in a debug build.

    If you're sure that your code is correct (so, you've had a code review and you've tested it extensively) then it is fine to leave out bounds checks in a release build for the sake of performance.

    If you are going to test the bounds in a debug build but not in a release build then you should probably use an assert in the debug build. asserts should be used to verify things that are always true. If you are not checking bounds inside of the function and your code is correct, then the value should never be out of bounds.