构造类的性能问题,C++
我知道这是一个简单的问题,但我不知道如何正确地完成我的想法。我正在使用 SFML,但您不需要了解它是如何工作的。 这是我的简单代码片段,用于生成图块并将它们分配给图块的 2D 向量: http://www.pastie.org/2665489
在构建TilePlane 对象,每个操作
(tilesMap[i]).push_back(tile)
花费的时间太长,我觉得我正在复制数据而不是使用更优雅的方法。那么在这种情况下,有什么好的方法可以解决这个问题呢?
I am aware that this is an easy problem but I don't know how to do properly what I have in mind. I am using SFML but you don't need to understand how it works.
Here is my simple code snippet that generate tiles and assign them to a 2D-vector of tiles:
http://www.pastie.org/2665489
During the construction of the TilePlane
object, each operation (tilesMap[i]).push_back(tile)
takes far too long and I feel that I am copying data instead of using a more elegant method. So in this case, what is the good method to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码中存在很多性能问题。如果瓶颈确实来自
push_back
,您应该采纳 Masoud 的建议,将指针推送到数组而不是值上。另一个建议是声明函数和构造函数以使用引用 - 例如:
不要
按值传递参数,而是强制创建副本,这可能会很昂贵。通过 const 引用传递可保证对象不被复制或修改。
You have a lot of performance issues in your code. If the bottleneck indeed comes from
push_back
, you should take Masoud's suggestion and push pointers onto the array and not values.Another suggestion is that you declare your functions and constructors to use references - for example:
instead of
Passing the parameter by value will force a copy to be created, which can be expensive. Passing by const reference guarantees the object is not copied or modified.
正如你所说,问题可能是
(tilesMap[i]).push_back(tile)
,当您将
tile
对象插入到列表中时,实际上您正在完全复制sf::Image
(因为copy-constructor
sf::Image
)。您应该将
tile
的指针放入列表中。如下所示:不要忘记,您必须在正确的时间
删除
tile_ptr
对象。例如,在~TilePlane()
中,您必须迭代列表并删除
图块对象。As you said maybe the problem is
(tilesMap[i]).push_back(tile)
,when you insert an object of
tile
to the list, in fact you are copying ansf::Image
entirely(Beacause ofcopy-constructor
ofsf::Image
).You should put pointers of
tile
s to the list. Something like below:Dont forget, you must
delete
tile_ptr
objects in right time. For example in~TilePlane()
, you must iterate the list anddelete
the tile objects.