我最近一直在为我的游戏引擎实现一个实体组件系统。每个实体都保留一个这样的组件映射:
组件.h
enum COMPONENT_INFO {
COMPONENT_POSITION = 0,
COMPONENT_PHYSICS,
COMPONENT_RENDERABLE
};
实体.h
class Entity {
public:
std::bitset<NUM_COMPONENTS> componentBits;
std::map<COMPONENT_INFO, Component*> components;
..
..
Component *getComponent(COMPONENT_INFO inf) {
return components[inf];
}
};
我的系统类会像这样更新每帧的每个实体:
void update(Entity *e, float delta) {
PositionComponent *cmp=(PositionComponent*)e->getComponent(COMPONENT_INFO::COMPONENT_PHYSICS);
//x += 1.0f;
cmp->x += 1.0f;
}
一切都按预期进行,但我在访问 map 时遇到了巨大的性能问题。当我创建 10000 个实体并遍历它们时(系统实际遍历),我得到 80 FPS 的蓝色空白系统(没有视觉效果,只有普通屏幕)。但是,当我注释掉访问部分并仅使用 x += 1.0f;
时,FPS 令人难以置信地增加到 1000。像那样:
void update(Entity *e, float delta) {
x += 1.0f; //btw the system has a local x value.
}
所以问题只是通过 map 访问组件。我还能在这样的系统上使用什么?或者我在访问 map 时做错了什么?
重要编辑:这只是一个试驾,我的意思是每个实体可能有很多组件,而不仅仅是 3 个。我写这些只是为了测试目的。
最佳答案
由于每个实体的组件数量似乎是固定的,我会放弃 map 并使用实体中的成员变量来保存每个组件,以及一个 getter。这也将避免在更新函数中进行强制转换:
class Entity {
private:
PositionComponent* m_positionComponent;
PhysicsComponent* m_physicsComponent;
RenderableComponent* m_renderableComponent;
public:
// initialize the components in the constructor
PositionComponent* getPositionComponent() {
return m_positionComponent;
}
// more getters for the other components
}
或者,如果您希望拥有更多组件类型并希望保持设计的灵 active ,您可能希望将它们存储在一个 vector 中,使用枚举值对其进行索引。这将完全避免 map 查找并为您提供更好的性能。
关于c++ - std::map 访问速度太慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17919964/