1

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)
    }
}
N4D4V
  • 102
  • 5
  • 2
    What did you find out when you measured them? – eerorika Jun 12 '20 at 17:13
  • 2
    You ask this question as if there is some sort of certain way of measuring performance that independent of compiler and platform etc. If you want to know which of these two methods is better then time them on your machine with your compiler. – john Jun 12 '20 at 17:13
  • 1
    I would guess that there is no difference because 1) compilers are very good at optimising code, and 2) the time taken will be dominated by the I/O anyway. But I'm only guessing, if you want to know time it for yourself. – john Jun 12 '20 at 17:15

1 Answers1

1

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.

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • I see, so at the end I can avoid the size recalculation at each iteration, and the rest is not important as long as my code is readable, thanks – N4D4V Jun 12 '20 at 18:01
  • consider providing `begin` `end` and use range loop: https://godbolt.org/z/ZcnH5z – Marek R Jun 12 '20 at 19:36