StackOverflow, like Wikipedia, is a dangerous place. It’s a place where you go to learn something you didn’t know you wanted to learn. In both cases, the risk is: are you going to resurface, half an hour later, much the wiser on the French Revolution, or perhaps some nitty gritty feature of the Garbage Collector? Or are you going to come out with an enhanced knowledge of the manufacturing technique used to create left handed drinking straws in the early 20th century (and the life of the mother of the creator, and the university they went to, and the wartime history of the town they grew up in)?
So it was a lucky happening that I bumped into a thread on StackOverflow a while back regarding how Math.Pow is implemented in the .Net framework. It’s one of these methods which leave you cold when you navigate to their implementation with Resharper/dotPeek – because it’s just a stub with a MethodImplOptions.InternalCall attribute on it. It’s basically a marker saying “this code is implemented with magic”.
But, as Eric Lippert says – there is no magic. Magic is just a place holder for a deeper understanding, in the same way as MethodImplOptions.InternalCall is a place holder for a lower level implementation.
The post leads on to a discussion of how methods marked with MethodImplOptions.InternalCall are actually implemented, where the implementation is, and how the jitter can even substitute some functions directly with a single machine code instruction.
In the post you can see the Sin, Cos, Sqrt, Round functions are eligible to be implemented as a direct machine code instruction. As Hans points out, this can lead to C# floating point code that’s actually faster than the same code in C++ that uses library functions.
So on this case, I managed to escape from StackOverflow intact, and with an increased knowledge of MethodImpl.InternalCall, which is something I had been curious about for over 10 years.