Entitas-csharp: Generated Code Optimization

Created on 2 Sep 2018  路  3Comments  路  Source: sschmid/Entitas-CSharp

Hi,

Currently Entitas' ComponentEntityGenerator is using CreateComponent for AddComponent/RemoveComponent.
This means (heavy) use of Generics which carries a small but non-trivial performance penality. I dont have any easy-to-share benchmarks, but it improved starting-performance slightly for our specific case.

        // current entitas
        var component = CreateComponent<${ComponentType}>(index);
        // suggested optimization
        var componentPool = GetComponentPool(index);
        var component = componentPool.Count > 0 ? (${ComponentType})componentPool.Pop() : new ${ComponentType}();

Related is use of Activator.CreateInstance for creation of entities. We've replaced this with a function passed as the last argument for Context constructor. The context caches this function and uses it instead of the generic version.

        readonly Func<TEntity> _createEntity;

        public Context(int totalComponents, int startCreationIndex, ContextInfo contextInfo, Func<IEntity, IAERC> aercFactory, Func<TEntity> createEntity) {
            //--- snip
            _createEntity = createEntity;  //  previous: (TEntity)Activator.CreateInstance(typeof(TEntity))
            //--- snip
        }
    public GameContext()
        : base(
            GameComponentsLookup.TotalComponents,
            0,
            new Entitas.ContextInfo(
                "Game",
                GameComponentsLookup.componentNames,
                GameComponentsLookup.componentTypes
            ),
            (entity) =>

#if (ENTITAS_FAST_AND_UNSAFE)
                new Entitas.UnsafeAERC()
#else
                new Entitas.SafeAERC(entity)
#endif
            ,
            () => new GameEntity()
        ) {

Cheers

Most helpful comment

Hi, thanks for the suggestion. I will try to find time to create a performance test, to see see the benefits
馃憤

All 3 comments

Hi, thanks for the suggestion. I will try to find time to create a performance test, to see see the benefits
馃憤

Interesting, I remember a long time ago, when I added component pooling, I was explicitly testing
CreateComponent
vs
CreateComponent

and the latter was faster. Tested again now and it's the other way around. I will update the generated code!

Passing in the an entity factory method speed things up by a factor of 2x, very nice!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FiveP picture FiveP  路  3Comments

LywOPUS picture LywOPUS  路  3Comments

KumoKairo picture KumoKairo  路  4Comments

fayte0618 picture fayte0618  路  5Comments

yuchting picture yuchting  路  4Comments