N4D4V
N4D4V

Reputation: 102

Performance difference for loops in C++

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:

  1. I am using an array instead of a vector on purpose.
  2. The class member _matrixElements is an array of floats created using new.
  3. 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)
    }
}

Upvotes: 1

Views: 178

Answers (1)

Marek R
Marek R

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

Related Questions