perf: Drastically Improved Memory Usage

TIL, records are not value types and are actually just reference types. So I was pretty much allocating from heap every time I used any of my data types (Like Vector2D). Needless to say, they are all now readonly structs as I originally intended them to be.
This commit is contained in:
2024-01-26 23:40:02 +03:00
parent c32add40ff
commit b14d10db0c
15 changed files with 88 additions and 49 deletions

View File

@@ -2,8 +2,8 @@ using System;
namespace Syntriax.Engine.Core;
public record EngineTime
(
TimeSpan Total,
TimeSpan Elapsed
);
public readonly struct EngineTime(TimeSpan Total, TimeSpan Elapsed)
{
public readonly TimeSpan Total { get; init; } = Total;
public readonly TimeSpan Elapsed { get; init; } = Elapsed;
}

View File

@@ -3,11 +3,14 @@ using System;
namespace Syntriax.Engine.Core;
[System.Diagnostics.DebuggerDisplay("{ToString(),nq}, Length: {Magnitude}, LengthSquared: {MagnitudeSquared}, Normalized: {Normalized}")]
public record Vector2D(float X, float Y)
public readonly struct Vector2D(float X, float Y)
{
public float Magnitude => Length(this);
public float MagnitudeSquared => LengthSquared(this);
public Vector2D Normalized => Normalize(this);
public readonly float X { get; init; } = X;
public readonly float Y { get; init; } = Y;
public readonly float Magnitude => Length(this);
public readonly float MagnitudeSquared => LengthSquared(this);
public readonly Vector2D Normalized => Normalize(this);
public readonly static Vector2D Up = new(0f, 1f);
public readonly static Vector2D Down = new(0f, -1f);
@@ -22,6 +25,8 @@ public record Vector2D(float X, float Y)
public static Vector2D operator *(Vector2D vector, float value) => new(vector.X * value, vector.Y * value);
public static Vector2D operator *(float value, Vector2D vector) => new(vector.X * value, vector.Y * value);
public static Vector2D operator /(Vector2D vector, float value) => new(vector.X / value, vector.Y / value);
public static bool operator ==(Vector2D left, Vector2D right) => left.X == right.X && left.Y == right.Y;
public static bool operator !=(Vector2D left, Vector2D right) => left.X != right.X || left.Y != right.Y;
public static float Length(Vector2D vector) => MathF.Sqrt(LengthSquared(vector));
public static float LengthSquared(Vector2D vector) => vector.X * vector.X + vector.Y * vector.Y;
@@ -72,4 +77,7 @@ public record Vector2D(float X, float Y)
=> left.X.ApproximatelyEquals(right.X, epsilon) && left.Y.ApproximatelyEquals(right.Y, epsilon);
public override string ToString() => $"{nameof(Vector2D)}({X}, {Y})";
public override bool Equals(object? obj) => obj is Vector2D objVec && X.Equals(objVec.X) && Y.Equals(objVec.Y);
public override int GetHashCode() => HashCode.Combine(X, Y);
}