473,569 Members | 2,648 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Operator overloading, C++ performance crappiness

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; // "unnecessar y" creation of temp variable

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

return temp; // "unnecessar y" 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(mat rix2, &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
51 3534
> > obj1 += obj2;
obj1 += obj3;


That is not going to be any faster than the plain slow operator+ in my
example. First you "add" (copy) obj2 into obj1, then you add obj3.
This is slower than just adding two variables straight out into a third.


Who mentioned the word copy?
Matrix& Matrix::operato r+=(const Matrix& rMatrix)
{}

No copy is created.
Aug 17 '05 #11
Kyle wrote:
you would want to get to left hand argument of operator=, but then how
do you know its there ?
Good point but the compiler can handle that. If no left-hand variable
is present then the compiler would generate a transient temp variable of
the return type.
what about:

foo( a + b );

operator+ would need to know about the context its used in than ...


That is still a lot uglier than "var3 = var1 + var2".

Jo
Aug 17 '05 #12

Jojo wrote:

[]
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).


Use expression templates. Refer to
http://osl.iu.edu/~tveldhui/papers/E.../exprtmpl.html

Aug 17 '05 #13
Christian Meier wrote:
obj1 += obj2;
obj1 += obj3;


That is not going to be any faster than the plain slow operator+ in my
example. First you "add" (copy) obj2 into obj1, then you add obj3.
This is slower than just adding two variables straight out into a third.

Who mentioned the word copy?
Matrix& Matrix::operato r+=(const Matrix& rMatrix)
{}

No copy is created.


LOL... That's why I said "add (copy)". The first addition is equivalent
to a copy. See:

1. obj1 is in "emtpy" state (this has overhead because it would need to
be initialied to all 0).

2. obj1 += obj2. This is essientially copying obj2 into obj1 because
obj1 now has the value of obj2. Overhead again.

3. obj1 += obj3. Now you finally do the operation you want where you
add obj2 (remember obj1==obj2 at this point) to obj3. This is really
were all the work is and the only required overhead.

That is slower than:

1. obj1 in completely uninitialized or otherwise unknown state (no overhead)

2. Directly set obj1 to the value of obj2 + obj3

Jo
Aug 17 '05 #14
Jojo wrote:

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):
You must have a compiler which is really bad at optimization.
In the following code, the timing is as follows:

operator+: 180 clock ticks
function add(): 240 clock ticks

So (thanks to the optimizer, which optimizes away the total overhead
of the temporary) the code using operator+ is actually *faster* then
your specialized function.

#include <iostream>
#include <ctime>

using namespace std;

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];
}

friend Matrix operator+( const Matrix& lhs, const Matrix& rhs );
};

inline Matrix operator +( const Matrix& lhs, const Matrix& rhs )
{
Matrix temp; // "unnecessar y" creation of temp variable

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

return temp;
}

int main()
{
Matrix a(2), b(3), c;
time_t start, end;

start = clock();
for( int j = 0; j < 100000; ++j )
c = a + b;
end = clock();

cout << end - start << endl;

start = clock();
for( int j = 0; j < 100000; ++j )
a.add( b, c );
end = clock();

cout << end - start << endl;
}

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; // "unnecessar y" creation of temp variable

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

return temp; // "unnecessar y" 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(mat rix2, &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

--
Karl Heinz Buchegger, GASCAD GmbH
Teichstrasse 2
A-4595 Waldneukirchen
Tel ++43/7258/7545-0 Fax ++43/7258/7545-99
email: kb******@gascad .at Web: www.gascad.com

Fuer sehr grosse Werte von 2 gilt: 2 + 2 = 5
Aug 17 '05 #15

"Jojo" <jo**@pleasenom orespamicanttak eitanymore.com> schrieb im Newsbeitrag
news:43******** *************** @authen.white.r eadfreenews.net ...
Christian Meier wrote:
obj1 += obj2;
obj1 += obj3;

That is not going to be any faster than the plain slow operator+ in my
example. First you "add" (copy) obj2 into obj1, then you add obj3.
This is slower than just adding two variables straight out into a third.

Who mentioned the word copy?
Matrix& Matrix::operato r+=(const Matrix& rMatrix)
{}

No copy is created.


LOL... That's why I said "add (copy)". The first addition is equivalent
to a copy. See:

1. obj1 is in "emtpy" state (this has overhead because it would need to
be initialied to all 0).

2. obj1 += obj2. This is essientially copying obj2 into obj1 because
obj1 now has the value of obj2. Overhead again.

3. obj1 += obj3. Now you finally do the operation you want where you
add obj2 (remember obj1==obj2 at this point) to obj3. This is really
were all the work is and the only required overhead.

That is slower than:

1. obj1 in completely uninitialized or otherwise unknown state (no

overhead)
2. Directly set obj1 to the value of obj2 + obj3

Jo


aaah, now I start to understand your "copy" :-)
OK, back to the beginning.
Your function add() is not totally bad. But the name "add" is a bit
confusing with your two parameters. What about something like "setToSum"?
Now to your parameters. Why don't use use *this for the object to be set? Is
there a reason why *this has to be unchanged?

void setToSum(const Matrix& first, const Matrix& second)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); ++i)
data[i] = first.data[i] + second.data[i];
}

This is perhaps a bit cleaner.

Greets Chris
Aug 17 '05 #16
Karl Heinz Buchegger wrote:
Jojo wrote:
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):

You must have a compiler which is really bad at optimization.
In the following code, the timing is as follows:

operator+: 180 clock ticks
function add(): 240 clock ticks

So (thanks to the optimizer, which optimizes away the total overhead
of the temporary) the code using operator+ is actually *faster* then
your specialized function.


Yes a good compiler could do that. I have not found one than can.

So the big question is what compiler are you using?

I'm using GCC (I tried versions 3.3 and 4.0).

Jo
Aug 17 '05 #17
Christian Meier wrote:
aaah, now I start to understand your "copy" :-)
OK, back to the beginning.
Your function add() is not totally bad. But the name "add" is a bit
confusing with your two parameters. What about something like "setToSum"?
Now to your parameters. Why don't use use *this for the object to be set? Is
there a reason why *this has to be unchanged?

void setToSum(const Matrix& first, const Matrix& second)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); ++i)
data[i] = first.data[i] + second.data[i];
}

This is perhaps a bit cleaner.

Greets Chris


True, but you can name it anything and the code will still look really
bad when things get complicated.

Nothing works as clean as "var3 = var1 + var2". There just doesn't seem
to be a way to do that efficiently in C++ (of course unless you have a
really good compiler as mentioned in another post; show me that compiler!).

Jo
Aug 17 '05 #18
"Jojo" <jo**@pleasenom orespamicanttak eitanymore.com> schrieb im Newsbeitrag
news:43******** *************** @authen.white.r eadfreenews.net ...
Christian Meier wrote:
aaah, now I start to understand your "copy" :-)
OK, back to the beginning.
Your function add() is not totally bad. But the name "add" is a bit
confusing with your two parameters. What about something like "setToSum"? Now to your parameters. Why don't use use *this for the object to be set? Is there a reason why *this has to be unchanged?

void setToSum(const Matrix& first, const Matrix& second)
{
for (unsigned i = 0; i < sizeof(data)/sizeof(int); ++i)
data[i] = first.data[i] + second.data[i];
}

This is perhaps a bit cleaner.

Greets Chris
True, but you can name it anything and the code will still look really
bad when things get complicated.


Also true, but a bit better than add(const Matrix&, Matrix*);

Nothing works as clean as "var3 = var1 + var2". There just doesn't seem
to be a way to do that efficiently in C++ (of course unless you have a
really good compiler as mentioned in another post; show me that

compiler!).

IMHO optimize away a temporary return value is support by many compilers....
Aug 17 '05 #19
Karl Heinz Buchegger wrote:
inline Matrix operator +( const Matrix& lhs, const Matrix& rhs )
{
Matrix temp; // "unnecessar y" creation of temp variable

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

return temp;
}


OK, _this_ is the answer I think I have been looking for. This method
is not the method I posted and this is indeed faster in GCC.

My method was:
Matrix operator+(const Matrix&)

Your method is:
operator+(const Matrix&, const Matrix&)

I did not know there was a two parameter version of operator+.

Thanks! Jo
Aug 17 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2851
by: Steve Sargent | last post by:
Hi: I'm trying to debug the following code, and it keeps looping on the if statement: public static bool operator == (OnlineMemberNode first, OnlineMemberNode second) { if(first == null) {
17
2494
by: Chris | last post by:
To me, this seems rather redundant. The compiler requires that if you overload the == operator, you must also overload the != operator. All I do for the != operator is something like this: public static bool operator !=(MyType x, MyType y) { return !(x == y); } That way the == operator handles everything, and extra comparing logic...
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8130
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7677
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3643
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
940
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.