By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,977 Members | 1,589 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,977 IT Pros & Developers. It's quick & easy.

Operator overloading, C++ performance crappiness

P: n/a
Is there any way to get to the left-hand side of an operator? Consider
the following (this is not meant to be perfect code, just an example of
the problem):

class Matrix
{
public:
int data[1024];

Matrix() {}

Matrix(int value)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
data[i] = value;
}

void add(const Matrix& obj, Matrix* output)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
output->data[i] = data[i] + obj.data[i];
}

Matrix operator +(const Matrix& obj)
{
Matrix temp; // "unnecessary" creation of temp variable

for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
temp.data[i] = data[i] + obj.data[i];

return temp; // "unnecessary" extra copy of output
}
};

For nice looking syntax you _really_ want to use the operator+ like:
matrix3 = matrix1 + matrix2;

However, that is some 50% slower than the _much_ uglier:
matrix1.add(matrix2, &matrix3);

If only there were a way to get to the left-hand argument of the
operator+ then it could be fast and easy to use. Consider the following
code which is not valid C++ and will not compile for this example:

Matrix as M
operator+(const Matrix& obj)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); i++)
M.data[i] = data[i] + obj.data[i];
}

That would be fast and clean to use. Is there any way to accomplish
this? Otherwise the situation is just ugly and there is no point in
using operator overloading for these types of situations (which really
defeats the purpose of operator overloading in the first place).

Thanks! Jo
Aug 17 '05
Share this Question
Share on Google+
51 Replies


P: n/a
Victor Bazarov wrote:

6703 is for add() method
11484 is for "c = a + b"

Yes, I believe that. I've tested on several compilers/systems and all
pretty much give the same result, 'add' is two-three times better. The
difference undoubtedly comes from the fact that the matrix needs to be
copied to and fro.


This is the main reason why we discourage operator=() in our codebase,
prefering the add() style of API. We've been bitten by performance hits
like this too often.
Aug 19 '05 #51

P: n/a

Victor Bazarov wrote:
Aleksey Loginov wrote:
[...]
i work with gcc 3.2, so can't get real results by myself...


Hmm... I didn't know gcc 3.2 was unable to produce real results...


good compiler, but he is 2 year's old... :)

Aug 22 '05 #52

51 Replies

This discussion thread is closed

Replies have been disabled for this discussion.