Reuse an ComponentDataFromEntity<T> instance in ComponentSystemBase.GetComponentDataFromEntity()

Small suggestion,

main intension of ComponentDataFromEntity is to speedup lookup of entity references.
It is typically returned by ComponentSystemBase.GetComponentDataFromEntity() .
To enhance performance even more it may be useful to optionally add an (optional) parameter to ComponentSystemBase.GetComponentDataFromEntity() providing a stored ComponentDataFromEntity to avoid creation of this struct and its internal array on the heap every time this method is called.

Here’s the source

    public unsafe struct ComponentDataFromEntity<T> where T : struct, IComponentData
    {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
        readonly AtomicSafetyHandle      m_Safety;
#endif
        [NativeDisableUnsafePtrRestriction]
        readonly EntityComponentStore*   m_EntityComponentStore;
        readonly int                     m_TypeIndex;
        readonly uint                    m_GlobalSystemVersion;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
        readonly bool                    m_IsZeroSized;          // cache of whether T is zero-sized
#endif
        LookupCache                      m_Cache;       
        //funcitons...
    }

The Only thing that changes every frame is m_GlobalSystemVersion;
that’s why you need to GetComponentDataFromEntity every frame.

LookupCache m_Cache; is used to speed up Has then Get Set.
readonly AtomicSafetyHandle m_Safety; should not change if I getting ECS source code right.
There’s no internal array it’s a pointer pointing directly to EntityComponentStore’s storage. And the size of the struct is trivial. Getting it every frame is not a big deal.
So if you really like to you can try cache it and change m_GlobalSystemVersion each frame;

2 Likes

Understood.
I simply assumed that there is an internal array. Thx for your explanation!