Search code examples
c#c++optimizationgame-developmententity-component-system

Function pointers vs polymorphism in a game engine ECS architecture


So I have a question about ECS and how to structure it in a way that's performant in C++. Say I want to have components that are just data, and systems that are just logic, and I want to execute all of the Update functions for all of the systems, passing them a list of component tuples to operate on.

Would having the systems submit their Update method delegates as function pointers to an update list be more performant than adding the systems themselves to that list and using polymorphism to call a virtual Update method? Or is it indifferent in terms of what option I go with?

I was also wondering if anything changes if say, this is implemented in C# for example with delegates/Actions.


Solution

  • The reason polymorphism would be slow (cliché) is that the v-table lookup requires reading a pointer in an unrelated (to your entity's data) memory location. The page fault this may cause could cause a context switch to the OS, if it needs to look up new pages.

    That applies when you have very tightly optimized code and put lots of care into what data gets loaded when. For example, if you were doing high-frequency-trading or hard real-time robot control, that would apply.

    In a game, where you'll have a bunch of different threads for different subsystem and a bunch of engine code doing various things, the overhead of a function pointer, polymorphism or even delegate will be pretty similar. They all incur extra indirection. The only difference is where the extra pointers will be stored, and whether those will be already loaded or not.

    The only sane suggestion is: profile to confirm. But in all likelihood, whatever is simpler and cleaner will be the best approach.