A question about operator*=

J

JustSomeGuy

I have a matrix class that I want to add this method to.

basically I want to multiply a matrix by a matrix or by a constant.
However, I don't want to return a matrix (refrence) from the method
as this might be a performance issue.

If one implements the method, then I suppose one is not 'required'
to return the result. However that doesn't sound like 'good' programming
style as others may not realise I've done this.

Consider these two statements:

1) a *= 2;
2) b = a *= 2;

Statement 1 doesn't make use of the return result of the *= operator, where
as
statement 2 does.

So is statement 1 faster than statement 2?
 
R

Roel Schroeven

JustSomeGuy said:
I have a matrix class that I want to add this method to.

basically I want to multiply a matrix by a matrix or by a constant.
However, I don't want to return a matrix (refrence) from the method
as this might be a performance issue.

Returning a matrix can be an expensive operation, just returning a
reference has minimal impact on the performance.
If one implements the method, then I suppose one is not 'required'
to return the result. However that doesn't sound like 'good' programming
style as others may not realise I've done this.

If you're afraid confusion might result, perhaps it's a better idea not
to use operator*=, but use a normal member function?
Consider these two statements:

1) a *= 2;
2) b = a *= 2;

Statement 1 doesn't make use of the return result of the *= operator, where
as
statement 2 does.

So is statement 1 faster than statement 2?

Of course, since it does less: the assigmnent to b doesn't happen. It
would be fairer to compare

a *= 2; b = a;
and
b = a *= 2;

I think there won't be much difference in performance. The first one is
easier to read though, in my opinion.
 
J

John Harrison

JustSomeGuy said:
I have a matrix class that I want to add this method to.

basically I want to multiply a matrix by a matrix or by a constant.
However, I don't want to return a matrix (refrence) from the method
as this might be a performance issue.

There's nothing inefficient about returning a reference. Returning a
reference from *= is normal.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top