Reflect is just too slow

Reflect is just too slow

After reducing collision objects in previous article and optimize memory usage, I think it is time to do some pressure test. So the entire scene is frozen when spawning 1440 bullets. The profile info looks like:

adding components is slow

The profile shows that every access operation rely on ‘Type.getClassName’ function, because Entity object uses [Class => value] Map to store components in traditional ECS framework. But Reflect is very slow, it takes 18% execution time just for adding components to Entity. There is second part:

you again!

Because Bullet Entity use a internal finite state machine to manage components, it still use Reflect. After counting each state, I find ‘Type.getClassName’ function takes about 40% of execution time just for access components. When creating lots of entity, the fps will decrease to 1 and hurt user experience.

So I have to use new approach: using flyweight pattern to store components and accessed by Entity id.

It requires refactoring all codes that adding / checking / removnig components, but still worth it:

FPS increases form 1 to 22 in deep profile mode, and 130 when closing profile. Now I can say:

Leave a Reply

Your email address will not be published. Required fields are marked *