具有元组成员的对象的移动构造函数的性能
我有一个关于移动构造函数、伪 C++ 类的性能的问题:
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;
};
当我移动 Foo1 类的对象时,它将初始化存储在元组中的所有对象的移动构造函数,对吗?这意味着,移动操作可能非常昂贵。
但是我移动 Foo2 类的对象整个移动操作要快得多,因为我只传递存储在智能指针中的数据的内部指针,对吗?
右值引用比左值引用更快,因为需要更少的复制操作,这是显而易见的。然而,使用移动构造函数从函数返回对象仍然比将相同的对象存储在智能指针中并返回智能指针更昂贵。
通过左值移动对象非常慢,通过智能指针移动对象非常快,通过右值移动对象则处于中间位置。
我没有看到r值的“威力”,因为它并不像很多人说的那么有效。恕我直言,使用智能指针而不是右值更好(我的意思是更快),并且代码优雅且清晰。我说得对吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你的班级有很多成员,那么你必须移动所有成员(或者足够让移动有意义)。这总是比移动单个(智能)指针更昂贵,但可能比复制更便宜。
但是,将数据存储在堆上以便可以通过指针访问它(以加快移动速度)将影响其余代码的性能,因为每次访问都必须取消引用指针。
分析并优化慢速部分。如果移动不是瓶颈,那么就采取措施使其余代码更快,反之亦然。
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.