I am using visual studio and are currently creating a game engine in c++, it's in 2D. The purpose is to learn modern game engine architecture and component based systems in general. This means that i have a very performance oriented mindset (even though performance isn't much of an issue when developing for 2D on modern hardware).
Would the compiler optimze something like this?
template<class T>
inline T & Scene::accessComponent(unsigned int id)
{
if (dynamic_cast(T*) < Transform > ) {
...
}
else if (dynamic_cast(T*) < Collidable > ) {
...
}
else if (dynamic_cast(T*) < AnotherComponentType > ) {
...
}
etc ...
}
I heard that if a function enters the same logic gate on sequential calls the compiler can optimize for future calls. Does this work with templated functions aswell? Do the compiler optimize if T is of the same type on sequential calls?
I cant profile anything because currently the code is a mess, different parts of the engine that would allow for a accessComponent call are not implemented yet. So i am kind of in the planning phase.
This code is something which certainly should not be done in performance-oriented code. It suffers from multiple branches. Logically, there are at least two branches with every dynamic_cast check: a branch generated by the compiler itself (to check RTTI) and a branch generated by your if
statement.
Branch predictors in modern hardware are powerful, but limited. At the bare minimum, their quantity is limited, and than if the distribution of events is more or less uniform, they fail.
And even when branch prediction succeeds, you still loose some cycles on the branch calculation itself.
I see no reason for dynamic cast at all. Since your classes are already polymorphic, just call corresponding virtual methods.