Is there an advantage to using pointers or references to return Boost matrices?

233 Views Asked by At

I'm using Boost to do some matrix algebra. I'm trying to understand if this optimization does anything. Original:

matrix<double> DoSomething(matrix<double> a, matrix<double> b)
{
    return a + b; //for example
}

Optimization:

matrix<double>* DoSomething(matrix<double>* a, matrix<double>* b)
{
    return *a + *b; //for example
}

Basically, I assumed that using pointers as the parameters and the return type would prevent copying a large object. After reading through the source code, I'm wondering if Boost ublas basically takes care of this. It seems like you're always dealing with a reference in Boost's code.

2

There are 2 best solutions below

0
On

That's not an optimization. In fact, it's a disaster. Your "optimized" code returns a pointer to a temporary object that no longer exists when the function returns. If you try to fix this:

matrix<double>* DoSomething(matrix<double>* a, matrix<double>* b)
{
    return new Matrix<double>(*a + *b); //for example
}

Well, look what you just did there. You just asked to create a copy, since your new matrix is copy-constructed from the temporary that results from summing a and b. Worse, this code is now no longer exception safe and it's easy to screw up in the caller and not release the allocated matrix.

So leave it alone. It's already optimized, and you can easily break it or make it worse.

2
On

If you want the best performance pass references (or pointers) and return with std::move :

matrix<double>&& DoSomething(matrix<double>& a, matrix<double>& b)
{
    return std::move(a + b); 
}

So you avoid to copy the arguments and the return value.But you can use std::move only in C++11.Otherwise return a matrix:

matrix<double> DoSomething(matrix<double>& a, matrix<double>& b)
{
    return a+b; 
}