我正在寻找一个需要满足以下要求的容器(针对游戏开发,尤其是实体管理):
例子:
Container<Entity> container;
// This pointer will always point to the player
Entity* player{new Entity};
container.add(player);
// Set some entities to "dead"
for(auto& e : container) if(e->type == "Enemy") e->die();
// Use erase-remove idiom on "dead" entities
container.cleanup();
// Player pointer is still valid
player->doSomething();
到目前为止,我已经尝试了两种不同的容器类型:
std::vector<std::unique_ptr<T>>
std::unique_ptr
)std::unique_ptr
)...和...
std::list<T>
即使看起来违反直觉,std::vector<std::unique_ptr<T>>
也比std::list<T>
按照我的基准测试更有效。
(对于更大的类型,std::list<T>
在插入过程中性能更高,但std::vector<std::unique_ptr<T>>
仍会获胜)。
我想知道是否有更好的替代方法std::vector<std::unique_ptr<T>>
。
理想地,替代方案应该是高速缓存友好的,以实现快速迭代,并允许用户即使添加/删除现有项目后也引用相同的项目(指针不应无效)。
通过性能测试,您正在做正确的事情。那是回答这个问题的唯一真实方法。
我所知道的唯一可能更快的方法是创建一个缓冲区。然后为创建一个自定义分配器,该分配器vector<unique_ptr<T>, custom_allocator<unique_ptr<T>>>
将从您的缓冲区分配。
还从同一缓冲区分配对象(这样,将unique_ptr的点指向缓冲区)。
为此,您必须知道上限,或者在超出限制时编写溢出逻辑。
使自定义分配器从缓冲区的中间向上增长。
使unique_ptrs的分配从缓冲区的中间向下增加。
只要整个缓冲区都适合高速缓存行,您就将尽可能快。这不是容易实现的,并且您当前的解决方案可能已经足够好了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句