There are some previous considerations to this message:
First, your difference of ~3.4 is around ~2 for me. That’s because you’re either using the MonoGame debug DLL, or you’re compiling your speed test project with Debug, or you’re running your project with F5 (instead of Ctrl+F5), or a combination of those. When testing speeds it’s better to test the “really release mode” (that’s MG release, release compilation, and Ctrl+F5)
Second, DateTime is not an accurate way to measure short amounts of time. It’s better to use Stopwatch.
That said, the reason it’s slower is that the Vector2.Distance call is not inlined, so a call is made. This is always slower than an inlined code execution. When in doubt about this kind of things, launch ILSpy and have a look at the generated code.
Workarounds? You could mark the Vector2.Distance in monogame source code as Aggressive Inlining, but I’m not sure if it’ll work. I’m not an expert but I think that the JIT plays a big role in inlining, so, being the code in another assembly it’s possible that the Vector2.Distance is inlined depending on the JIT. You may get it inlined in net core 3, but not on a previous version.
Additionally the method call has to convert the float back to double to store it in ‘answer’.
To make a fair comparison you should make double float and call ‘answer = (float)Math.Sqrt((pos2.X - pos1.X) * (pos2.X - pos1.X) + (pos2.Y - pos1.Y) * (pos2.Y - pos1.Y));’
My guess is that most of the cycles are wasted on copying the two vectors.
Try the faster Vector2.Distance(ref pos1, ref pos2, out answer);
It depends why are you trying to get the distance, my personal advice is that if you want just to compare between two or more distances to know which one is closer or farther from your reference point use the distance square to compare how far those points are, so I don’t do the Math.Sqrt and save a lot of cycles, I get the same result since I don’t care about the distance value but I care about the order.
Thank you for posting about MathF. For some reason I wasn’t aware of this and was using Math for calculations when MonoGame’s library didn’t have the features I needed. Flows much nicer using MathF with floating point numbers.