I guess this might be ancient and was never changed by the Monogame Team. I noticed this while playing around with performance profiling and noticed my custom struct which essentially does the same thing as Vector2 when calling the operators +,-,*,/ performed faster than Vector2. I checked with System.Numerics.Vector2
which had similar performance to my own struct.
I took a look into the source code and found that Microsoft.Xna.Framework.Vector2
, for some reason, creates 2 copies on every + operation by calling += on it (if I’m not mistaken, I think that’s what happens when you try to change a value on a struct) instead of just creating one new(x1 + x2, y1 + y2)
Microsoft.Xna.Framework.Vector2
public static Vector2 operator +(Vector2 value1, Vector2 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
return value1;
}
System.Numerics.Vector2
public static Vector2 operator +(Vector2 left, Vector2 right)
{
return new Vector2(left.X + right.X, left.Y + right.Y);
}
My custom Size struct
public static Size operator +(Size s1, Size s2)
{
return new Size(s1.Width + s2.Width, s1.Height + s2.Height);
}
Same thing with all other operators. My performance profiling code (using DotNetBenchmark
) just calls +,*,-,/ a million times (and , granted, creates new structs, but I doubt that’s relevant to the actual difference, given the constructors of every struct just assigns 2 field values, ie does the same thing for all 3 test cases).
[Benchmark]
public void MicrosoftXnaVector2()
{
var x = new Microsoft.Xna.Framework.Vector2(0, 0);
for (var i = 1; i < it; i++)
{
x += new Microsoft.Xna.Framework.Vector2(i, i);
x *= new Microsoft.Xna.Framework.Vector2(i, i);
x -= new Microsoft.Xna.Framework.Vector2(i, i);
x /= new Microsoft.Xna.Framework.Vector2(i, i);
}
}