Question

I have a question about performance of move constructor, pseudo C++ class:

typedef tuple<std::string, std::vector<double>, ...and more...> FooTupleMember;

class Foo1
{
    public:
        Foo1::Foo1 (Foo1&& object) :
            member (std::move (object.member))
        {
            // ...
        }
    private:
        FooTupleMember member;
};

class Foo2
{
    public:
        Foo2::Foo1 (Foo2&& object) :
            member (std::move (object.member))
        {
            // ...
        }
    private:
        std::unique_ptr<FooTupleMember> member;
};

When I move object of Foo1 class it will initialize move constructors of all object stored in tuple right? This mean, that move operation can be quite expensive.

But I move object of Foo2 class whole move operation is much faster because i only pass internal pointer of data stored in smart pointer, right?

R-value reference are faster then l-value reverence, because the require much less copy operations, that's obvious. However returning object from function using move constructor is still more expensive then storing the same object in smart pointer and returning smart pointer.

Moving objects via l-value is very slow, moving it via smart pointer is very fast and moving it via r-value is somewhere in the middle.

I don't see "the power" of r-value, because it's not as effective as many people say. Using smart pointer instead of r-value is IMHO better (I mean faster) and it code elegant and clear. Am I right?

Was it helpful?

Solution

If your class has a lot of members then you have to move all of them (or enough for the move to make sense anyway). This is always going to be more expensive than moving a single (smart) pointer, but is likely less expensive than copying.

However, storing your data on the heap so you can access it through a pointer (to make move fast) will impact the performance of the rest of your code, since every access must dereference the pointer.

Profile, and optimize the slow bits. If moving isn't a bottleneck, then do what makes the rest of your code faster, and vice versa.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top