I am in a situation where I have game objects that have a virtual function Update(). There are a lot of game objects (currently a little over 7000) and the loop calls update for all of them (amongst other things). My colleague suggested that we should remove the virtual function altogether. As you can imagine, this will take a lot of refactoring.
I have seen this answer but in my case, profiling means I have to change a lot of code. So before I even think of starting I thought I’d ask here for opinion on whether refactoring is worth it in this case.
Note that I have profiled other parts of the loop and have been trying to optimize the parts that are taking the longest. I suspect that the virtual function calls in this case is something I should not worry about, but I cannot be sure until I profile and I cannot profile until I change the code (which is a lot). Also note that some update functions are very small while others are larger more complex.
EDIT: There are multiple answers that give great insight, so anybody who stumbles onto this question in the future, have a look at all the answers and not just the selected one.
If you can’t profile, have a look at the assembler code to get an idea how expensive the lookup really is. It might be a simple indirect jump which costs almost nothing.
If you need to refactor, here is a suggestion: Create lots of “UpdateXxx” classes which know how to call the new non-virtual
update()method. Collect those in an array and then callupdate()on them.But my guess is that you won’t save much, especially not with only 7K objects.
Note on profiling: If you can’t use a profiler (makes me wonder why not), time the calls to
update()and log calls which take longer than, say, 100ms. The timing isn’t expensive and it allows you to quickly figure out which calls are most expensive.