Consider the following C++
class and struct in
typedef struct MatrixDims
{
int rows, cols;
} MatrixDims;
class Matrix
{
private:
float *_matrixElements;
MatrixDims _matrixDims;
public:
Matrix(int rows, int cols);
~Matrix();
void printMatrix() const;
}
Notes:
- I am using an array instead of a vector on purpose.
- The class member
_matrixElements
is an array offloats
created usingnew
. - The matrix here is implemented using 1-dimentional array.
My question:
Is there any performance difference between the two following implementations of the method printMatrix()
?
void Matrix::printMatrix() const
{
for (size_t i = 0; i < this->_matrixDims.rows * this->_matrixDims.cols; i++) // (1)
{
cout << this->_matrixElements[i]; // (2)
}
}
void Matrix::printMatrix() const
{
size_t size = this->_matrixDims.rows * this->_matrixDims.cols; // (3)
float *mat = this->_matrixElements; // (4)
for (size_t i = 0; i < size; ++i) // (5)
{
cout << mat[i]; // (6)
}
}