Search Unity

[Performance Question] Accessing individual entity components in an NativeArray<ArchetypeChunk>.

Discussion in 'Entity Component System' started by sstrong, Apr 9, 2019.

  1. sstrong

    sstrong

    Joined:
    Oct 16, 2013
    Posts:
    2,255
    When looping though chunks on the main thread in OnUpdate, is it better to return a NativeArray of a component and access a few of them by index, or (somehow) get an individual component on one of the entities within the chunk?

    Code (CSharp):
    1. ArchetypeChunkComponentType<myComponent> myComponentType = GetArchetypeChunkComponentType<myComponent>();
    2. NativeArray<ArchetypeChunk> chunks = myEntityQuery.CreateArchetypeChunkArray(Allocator.TempJob);
    3.  
    4. int chunksLength = chunks == null ? 0 : chunks.Length;
    5. for (int chunkIndex = 0; chunkIndex < chunksLength; chunkIndex++)
    6. {
    7.   ArchetypeChunk chunk = chunks[chunkIndex];
    8.  
    9.   NativeArray<myComponent> myComponents = chunk.GetNativeArray(myComponentType);  
    10.  
    11.   // Loop through the entities in this chunk
    12.   int chunkSize = chunk == null ? 0 : chunk.Count;
    13.   for (int entityIndex = 0; entityIndex < chunkSize; entityIndex++)
    14.   {
    15.      // process raycast results from a ScheduleBatch
    16.  
    17.  
    18.      // if something did collide with something
    19.      if (some rare condition)
    20.      {
    21.         SomeMethod(myComponents[entityIndex].somefield);
    22.      }
    23.   }
    24. }
    How much overhead is there in the following:

    Code (CSharp):
    1. NativeArray<myComponent> myComponents = chunk.GetNativeArray(myComponentType);
     
  2. dartriminis

    dartriminis

    Joined:
    Feb 3, 2017
    Posts:
    157
    ArchetypeChunk.GetNativeArray() is the recommended method to get data from chunks. Remember that a chunk is a 16KB chunk of memory that contains all the component data for a group of entities. So within the bounds of a single chunk, you can use GetNativeArray on any number of component types and index through them without incurring a cache miss.
     
  3. sstrong

    sstrong

    Joined:
    Oct 16, 2013
    Posts:
    2,255
    So, GetNativeArray() doesn't need to allocate any memory it's just returning a pointer to a block of memory that contains the component data for those entities within the chunk?
     
  4. dartriminis

    dartriminis

    Joined:
    Feb 3, 2017
    Posts:
    157
    Correct.
     
    sstrong likes this.
  5. JooleanLogic

    JooleanLogic

    Joined:
    Mar 1, 2018
    Posts:
    447
    Also I don't think the chunks will ever be null in those contexts.