Speed comparison - Template specialization vs. Virtual Function vs. If-Statement
- by Person
Just to get it out of the way...
Premature optimization is the root of all evil
Make use of OOP
etc.
I understand. Just looking for some advice regarding the speed of certain operations that I can store in my grey matter for future reference.
Say you have an Animation class. An animation can be looped (plays over and over) or not looped (plays once), it may have unique frame times or not, etc. Let's say there are 3 of these "either or" attributes. Note that any method of the Animation class will at most check for one of these (i.e. this isn't a case of a giant branch of if-elseif).
Here are some options.
1) Give it boolean members for the attributes given above, and use an if statement to check against them when playing the animation to perform the appropriate action.
Problem: Conditional checked every single time the animation is played.
2) Make a base animation class, and derive other animations classes such as LoopedAnimation and AnimationUniqueFrames, etc.
Problem: Vtable check upon every call to play the animation given that you have something like a vector<Animation>. Also, making a separate class for all of the possible combinations seems code bloaty.
3) Use template specialization, and specialize those functions that depend on those attributes. Like template<bool looped, bool uniqueFrameTimes> class Animation.
Problem: The problem with this is that you couldn't just have a vector<Animation> for something's animations. Could also be bloaty.
I'm wondering what kind of speed each of these options offer? I'm particularly interested in the 1st and 2nd option because the 3rd doesn't allow one to iterate through a general container of Animations.
In short, what is faster - a vtable fetch or a conditional?