**Result:** The square root of 4 is 2. We see 2.0 because Math.sqrt returns a double.

**Tip:** For cases when we do not need fractional values, we can cast the result of Math.sqrt to an int.

**Version 1:** In this version of the code we call Math.sqrt repeatedly—no caching is used here.

**Version 2:** We use a double array cache of 100 Math.sqrt values. We access those values many times.

**Result:** Accessing array elements is more than ten times faster than calling Math.sqrt each time.

© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.

Home

Dot Net Perls