I have a question about comparing the speed of Vector.Length and Math.sqrt. I used the following code for comparing the speed.
int cnt = 100000;
double result = 0;
Vector A = new Vector(1.342,2.0);
Vector B = new Vector(5.1234,2.0);
Stopwatch sw = new Stopwatch();
sw.Start();
while(cnt-- > 1)
{
Vector AB = A-B;
result = AB.Length;
}
sw.Stop();
System.Console.WriteLine("Vector : " + sw.Elapsed);
sw.Reset();
cnt = 100000;
sw.Start();
while(cnt-- >1)
{
result = Math.Sqrt((B.X-A.X)*(B.X-A.X)+(B.Y-A.Y)*(B.Y-A.Y));
}
sw.Stop();
System.Console.WriteLine("Sqrt : " + sw.Elapsed);
Result :
Vector : 00:00:00.0019342
Sqrt : 00:00:00.0041913
The result shows that Vector.Length
is faster than Math.Sqrt()
.
I think Vector.Length
calculates length by using Math.Sqrt()
too. then Vector.Length
is equal or Slower than Math.Sqrt()
.
Why is it different from what I think? How Vector.Length is calculated?