Reputation: 102
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:
_matrixElements
is an array of floats
created using new
.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)
}
}
Upvotes: 1
Views: 178
Reputation: 37512
First of all in C
and C++
there is "AS IF" rule. Here is some SO answer about that.
This means that if you enable compiler optimizations there should be no significant differences.
In fact for such simple modification I wouldn't be surprised if final machine code is exactly same. So keep your code readable.
I did compared both versions and fist version recalculates total size of matrix for each iteration. Compiler assumes that rows
or cols
values can change when std::basic_ostream<char, std::char_traits<char> >& std::basic_ostream<char, std::char_traits<char> >::_M_insert<double>(double)
is called.
Note that this operation is quite fast so when you do a measurement I doubt you will be able to measure any difference.
Upvotes: 1