Search code examples
c++11visual-studio-2012optimizationconstructormove

optimizing class construction in c++


I have a class:

class A
{
    double a;
    map <int, double> b;
    public:
    A():a(0.0){}
    A(const double aa, const map <int, double> & bb): a(aa), b(bb){}
    A(double && aa, map <int, double> && bb):a(aa), b(bb) {} 
};

The optimizer (VS2012) shows line A(a1*b1, std::move(bmap)) takes most of the time.

Am I missing something here that can speed up the object construction? I started learning move constructors only recently, so I am not sure if my move constructor or its usage optimal or not.

Little bit more on the code: I have

 A operator *( double in)
 {
  if(in !=0.0)
    {
     map<int, double> tmp(b); //second bottleneck
     for(auto & itr: tmp)
        tmp.second *= in;
     return A(in * a, std::move(tmp)); //first optimization bottleneck
    }
  return A();
 }

Solution

  • Not sure if this is the culprit of your performance issues, but you're not actually moving tmp into A::b. You need to move bb into A::b, because bb is an lvalue:

    A(double && aa, map <int, double> && bb):a(aa), b(std::move(bb)) {} 
    //                                                ^^^^^^^^^^^^^
    

    Here's a minimal example on wandbox that illustrates the issue.