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

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.

Entities.ForEach((Entity e, ref Translation translation, ref Rotation rotation) =>
{
     if(IndexRef.TryGetValue(e, out int item))
     {
            // Does nothing
     }
}

Entities.ForEach generates garbage because you are creating a delegate every time you call it unless cached.

Great article on delegates and garbage.

-edit-

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

private EntityQueryBuilder.F_EDD<Translation, Rotation> method;

start{
    this.method = YOURMETHOD;
}

update {
    Entities.ForEach(this.method);
}

private void YOURMETHOD(Entity e, ref Translation translation, ref Rotation rotation)
{
}

I consider it an issue with Entities.ForEach and hope they can somehow fix it with IL2CPP at some point.

3 Likes

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!