How to avoid outer closure garbage?

Hi everyone! I am trying to avoid creating garbage. I’ve seen this post about avoiding garbage with outer closures. I’ve tried the delegate solution however I got an error that says;

error DC0044: Entities.ForEach can only be used with an inline lambda. Calling it with a delegate stored in a variable, field, or returned from a method is not supported.

So, I guess this is not supported anymore. Is there an alternative way? Thanks all!

For the context, here is the code;

var thrust = _playerControls.Ship.Thrust.ReadValue<float>();

Entities
    .WithAll<PlayerSpaceship, SpaceshipMotorInput>()
    .ForEach((ref SpaceshipMotorInput input) =>
    {
        // outer closure of 'thrust' variable
        input.Thrust = thrust;
    }).Schedule();

Entities.ForEach does not produce garbage on its own despite contrary beliefs.
Since code you write is actually replaced by the codegen (by using source generators).
Check generated code for the system for more details.

If you’re using Rider, you can turn off analysis for it with a comment in a file such as:

   // Replaced by codegen
   // ReSharper disable HeapView.ClosureAllocation
   // ReSharper disable HeapView.DelegateAllocation

I’m using it as a part of template. Rider is good, but does not include proper analysis for EFE.
Though be careful if used with managed systems and doing tricky stuff, as those will disable analysis delegate / capture analysis for the whole file.

What is not supported though is managed objects with .Schedule. Counting delegates & anonymous classes.

If you want to read value from separate Entity inside job - use either ComponentDataFromEntity or ComponentLookup depending on what version of Entities you’re using.

3 Likes