Advertisement

What to use for arbitrary dimension matrices in a real time physics engine.

Started by December 12, 2019 03:34 PM
2 comments, last by SFSpoto 4 years, 11 months ago

Hi all, I'm implementing the rigid body physics in C++ for learning purpose. Until now I used glm library to represent 3x3 and 4x4 matrices but now I need to represent arbitrary NxM matrices whose dimension is known at run time. So I wonder which is the best way to represent them.

I run into the following alternatives:

  • std::vector<std::vector<float>>: simple to handle, but I'm afraid of the possible overehead of the data structure
  • float**: a pointer to pointer, I think it's the more efficient solution but needs additional code to manage carefully the memory allocation/deallocation
  • using c++ smart pointers: I think this solution needs less effort than the second one, but again I wonder how much is the overhead


Any thought ?

Thank you!


std::vector<float> matrix;
int num_columns;
float &element(int row, int column) {
  return matrix[column + row * num_columns];
}

The overhead in the std::vector is insignificant compared to overhead of dynamic memory allocation, but you really want to keep your matrix data in a single block of memory for optimal data locality.

Advertisement

Thank you

I guess that optimal data locality implies that accessing consecutive memory locations is faster than address each matrix row at a different location with the pointer (is this really slow ?), even if with your solution you have the overhead due the index computation (column + row * num_columns).

This topic is closed to new replies.

Advertisement