Why is square root such a slow operation?

Athena picture Athena · Mar 11, 2014 · Viewed 7.2k times · Source

I've been warned by numerous programmers not to use the square root function, and instead to raise numbers to the half power. My question is twofold:

  1. What is the perceived/real performance benefit to doing this? Why is it faster?

  2. If it really is faster, why does the square root function even exist?

Answer

Dmitry Bychenko picture Dmitry Bychenko · Mar 11, 2014

I've performed a simple test:

  Stopwatch sw = new Stopwatch();

  sw.Start();

  Double s = 0.0;

  // compute 1e8 times either Sqrt(x) or its emulation as Pow(x, 0.5)
  for (Double d = 0; d < 1e8; d += 1)
    // s += Math.Sqrt(d);  // <- uncomment it to test Sqrt
    s += Math.Pow(d, 0.5); // <- uncomment it to test Pow

  sw.Stop();

  Console.Out.Write(sw.ElapsedMilliseconds);

The (averaged) outcome at my workstation (x64) is

  Sqrt:  950 ms 
  Pow:  5500 ms

As you can see, more specific Sqrt(x) 5.5 times faster than its emulation Pow(x, 0.5). So it's just one more legend (at least in C#) that Sqrt is that slow one should prefer Pow substitution