Search Unity

Why is calling a Native Array in a ComponentSystem Entities.Foreach generating garbage?

Discussion in 'Entity Component System' started by 8bitgoose, Aug 24, 2019.

  1. 8bitgoose

    8bitgoose

    Joined:
    Dec 28, 2014
    Posts:
    448
    I am trying to sync up some transforms with an Entity. I don't wanna use the built in stuff from Unity, too heavy for my needs. But I am wondering why this is generating garbage. I am just trying to get a struct value. It generates garbage (4k instances for some reason).

    I really don't understand. No garbage should be generated here. I am not generating anything, it is a Native Array, so no garbage should come out of that. Is boxing happening somehow?

    Or is there a better way. I want to keep a list of Transforms accessible so that the GameObject Transform can push it's position on the entity transform for physics reasons.

    Code (CSharp):
    1.  
    2. Entities.ForEach((Entity e, ref Translation translation, ref Rotation rotation) =>
    3. {
    4.      if(IndexRef.TryGetValue(e, out int item))
    5.      {
    6.             // Does nothing
    7.      }
    8. }
     
  2. tertle

    tertle

    Joined:
    Jan 25, 2011
    Posts:
    3,761
    Entities.ForEach generates garbage because you are creating a delegate every time you call it unless cached.

    https://jacksondunstan.com/articles/3765

    Great article on delegates and garbage.

    -edit-

    if you want to avoid garbage you need to do something like this

    Code (CSharp):
    1. private EntityQueryBuilder.F_EDD<Translation, Rotation> method;
    2.  
    3. start{
    4.     this.method = YOURMETHOD;
    5. }
    6.  
    7. update {
    8.     Entities.ForEach(this.method);
    9. }
    10.  
    11. private void YOURMETHOD(Entity e, ref Translation translation, ref Rotation rotation)
    12. {
    13. }
    I consider it an issue with Entities.ForEach and hope they can somehow fix it with IL2CPP at some point.
     
    Last edited: Aug 24, 2019
    pal_trefall, Razmot and thelebaron like this.
  3. 8bitgoose

    8bitgoose

    Joined:
    Dec 28, 2014
    Posts:
    448
    Ohhhhhh, I am creating a new action. I hate delegates and stay away from them usually. Of course, what a dummy

    Thanks for the help. You have saved me so much time. I had no idea how that was working. I tend to keep to jobs stuff unless I am affecting the world transforms in Old Unity.

    Edit: Updated everything and no garbage. I can't thank you enough @tertle. You are a lifesaver!
     
    Last edited: Aug 24, 2019