Fast and useful way of storing matrix values in C#
c#, math, matrix, performance, usability
Solution
You could use a two dimensional array:
float[,] matrix = new float[4,4];
This is different than a jagged array:
float[][] matrix = new float[][4];
A two dimensional array is, underneath, stored as one big one dimensional array. The class simply abstracts that away from you and provides accessors that provide two (or more) dimensions. Because it is stored as a one dimensional array in the back end you will maintain cache/memory locallity.
Problem
I need to create a 4x4 matrix class for a 3D engine in C#. I have seen some other engines storing the matrix values in single float member variables / fields like this: ``` float m11, m12, m13, m14 float m21, m22, m23, m24 float m31, m32, m33, m34 float m41, m42, m43, m44 ``` However, I thought storing them in a two dimensional array would be more useful for transformations / calculations with the matrices: ``` float[4][4]; ``` I also thought of a one dimensional array - but it looks less self explanatory and wouldn't give me an advantage over the first option: ``` float[16]; ``` In C++, I always used the "union" keyword to have all of the above storing possibilites at once. However, C# does not seem to have this keyword, so I have to decide which one I want to use. What is the fastest way of storing the 4x4 matrix when applying transformations etc.? Which option would you choose when thinking about usability?