I'm trying to implement a component based architecture on a game engine project. Each GameObject has an unordered_map
that holds a pointer to Component
base class. At this point, I only have one component derived class, which is the Transform
class. I wanted to implement this component based architecture similar to the Unity's convention: I want to get a component of game object by calling the member template function like GetComponent<Transform>()
.
Here are the headers:
Component.h
enum type{
TRANSFORM // more will be added later
};
class Component // base class
{
public:
Component() : _owner(NULL) {}
virtual ~Component(){}
static type Type;
protected:
GameObject* _owner;
};
Transform.h
class Transform : public Component
{
public:
Transform();
~Transform();
static type Type;
void Rotate(float deg);
// to be encapsulated later on
Vector2D _position;
float _rotation;
Vector2D _scale;
};
GameObject.h
class GameObject
{
public:
GameObject();
~GameObject();
void Update();
//and more member functions
template<class T>
T* GetComponent();
private:
// some more private members
unordered_map<type, Component*> _componentList; // only 1 component of each type
};
template<class T>
T* GameObject::GetComponent()
{
return static_cast<T*>(_componentList[T::Type]);
}
My initial implementation used std::vector
for keeping Component*
and the application ran at 60 fps (I also have a frame rate controller, which just limits the FPS to 60). When I changed to the unordered_map
for accessing those component pointers, the performance went downhill to 15 FPS.
I only draw two quads and I call GetComponent<Transform>()
only 6 times per frame at this point, so there is not much going on in the scene.
What I tried?
I tried to use const char*
, std::string
, type_info
and finally enum type
as key values for the unordered_map
but nothing really helps: all implementations got me 15-16 FPS.
What causes this performance issue? How can I isolate the issue?
I hope I provided enough detail, feel free to ask for more code if necessary