Search code examples
c#c#-3.0base-class-library

Are there significant performance gains inherent in using .NET's built in classes?


Quick little question...

I know that sometimes in other languages libraries have part of their code written in platform-specific straight C for performance reasons. In such cases you can get huge performance gains by using library code wherever possible.

So does the .NET platform do this? Is Microsoft's implementation of the Base Class Library optimized in some way that I can't hope to match in managed code?

What about something little like using KeyValuePair as a type-safe tuple struct instead of writing my own?


Solution

  • As far as I know, the .NET Framework hasn't been compiled in a way that creates hooks into some otherwise-inaccessible hardware acceleration or something like that, so for simple things like KeyValuePair and Tuple, you're probably safe rolling your own.

    However, there are a number of other advantages to using standard framework classes, and I'd hesitate to write my own without a strong reason.

    1. They're already written, so why give yourself extra work?
    2. Microsoft has put their code through a pretty rigorous vetting process, so there's a good chance that their code will be more correct and more efficient than yours will.
    3. Other developers that have to look at your code will know exactly what to expect when they see standard framework classes being used, whereas your home-brewed stuff might make them scratch their heads for a while.

    Update

    @gordy also makes a good point, that the standard framework classes are being used by everybody and their dog, so there will be a slight performance gain simply due to the fact that:

    1. the class likely won't have to be statically instantiated or just-in-time compiled just for your code,
    2. the class's instructions are more likely to already be loaded in a cache, since they'll likely have been used recently by other parts of code. By using them, you're less likely to need to load the code into a cache in the first place, and you're less likely to be kicking other code out of the cache that's likely to be used again soon.