-
I was very surprised by this behavior! Trying to squeeze out every bit of performance I can, and I discovered this: public class MovementSystem : BaseSystem<World, float> {
public MovementSystem(World world) : base(world) { }
private readonly QueryDescription movingQuery =
new QueryDescription().WithAll<Position, Angle, Speed>();
public override void Update(in float deltaTime) {
World.Query(in movingQuery,
(ref Position position, ref Angle angle, ref Speed speed) => {
// Method A: Runs in ~2.5ms (60,000 entities)
position.X += (float) Math.Cos(angle.Value) * speed.Value;
position.Y += (float) Math.Cos(angle.Value) * speed.Value;
// Method B: Runs in ~1.8ms (60,000 entities)
position = new Position {
X = position.X + (float) Math.Cos(angle.Value) * speed.Value,
Y = position.Y + (float) Math.Sin(angle.Value) * speed.Value
};
});
}
} This is a .NET 7 standalone CLI build, running in release mode with code optimizations, (Windows/Rider). I was surprised that this is more efficient. Is this expected? If so, perhaps it should be included in Performance Tips, as the current similar examples demonstrate updating the fields separately. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
This is really very very interesting... and in a way it doesn't make sense. The first thing that strikes me is that it is C# specific and probably has nothing to do with the ECS. That makes it even more interesting. The update of single fields should be more efficient in every programming language. Replacing fields needs an additional constructor which should make the whole thing slower :0 I am indeed a bit confused by this, maybe you should have a look at the IL code / assembly code ^^ |
Beta Was this translation helpful? Give feedback.
-
Did some research and checked the IL in sharplab : Asigning the attributes directly produces less IL and assembly code. A benchmark could solve this question once and for all ^^ |
Beta Was this translation helpful? Give feedback.
-
Benchmark: https://gist.github.com/Stovoy/04229a08b1caf699ecec69597426344f Results:
My current guess is that this is some runtime-optimization coming from the JIT compiler optimizing these loops over spans. |
Beta Was this translation helpful? Give feedback.
Benchmark: https://gist.github.com/Stovoy/04229a08b1caf699ecec69597426344f
Results:
My current guess is that this is some runtime-optimization coming from the JIT compiler optimizing these loops over spans.