Do C# Generics Have a Performance Benefit?

前端 未结 12 1099
感动是毒
感动是毒 2020-12-13 04:26

I have a number of data classes representing various entities.

Which is better: writing a generic class (say, to print or output XML) using generics and interfaces,

相关标签:
12条回答
  • 2020-12-13 04:42

    Generics in C# are truly generic types from the CLR perspective. There should not be any fundamental difference between the performance of a generic class and a specific class that does the exact same thing. This is different from Java Generics, which are more of an automated type cast where needed or C++ templates that expand at compile time.

    Here's a good paper, somewhat old, that explains the basic design: "Design and Implementation of Generics for the .NET Common Language Runtime".

    If you hand-write classes for specific tasks chances are you can optimize some aspects where you would need additional detours through an interface of a generic type.

    In summary, there may be a performance benefit but I would recommend the generic solution first, then optimize if needed. This is especially true if you expect to instantiate the generic with many different types.

    0 讨论(0)
  • 2020-12-13 04:42

    I did some simple benchmarking on ArrayList's vs Generic Lists for a different question: Generics vs. Array Lists, your mileage will vary, but the Generic List was 4.7 times faster than the ArrayList.

    So yes, boxing / unboxing are critical if you are doing a lot of operations. If you are doing simple CRUD stuff, I wouldn't worry about it.

    0 讨论(0)
  • 2020-12-13 04:43

    Generics are one of the way to parameterize code and avoid repetition. Looking at your program description and your thought of writing a separate class to deal with each and every data object, I would lean to generics. Having a single class taking care of many data objects, instead of many classes that do the same thing, increases your performance. And of course your performance, measured in the ability to change your code, is usually more important than the computer performance. :-)

    0 讨论(0)
  • 2020-12-13 04:45

    There's a significant performance benefit to using generics -- you do away with boxing and unboxing. Compared with developing your own classes, it's a coin toss (with one side of the coin weighted more than the other). Roll your own only if you think you can out-perform the authors of the framework.

    0 讨论(0)
  • 2020-12-13 04:50

    According to Microsoft, Generics are faster than casting (boxing/unboxing primitives) which is true. They also claim generics provide better performance than casting between reference types, which seems to be untrue (no one can quite prove it).

    Tony Northrup - co-author of MCTS 70-536: Application Development Foundation - states in the same book the following:

    I haven’t been able to reproduce the performance benefits of generics; however, according to Microsoft, generics are faster than using casting. In practice, casting proved to be several times faster than using a generic. However, you probably won’t notice performance differences in your applications. (My tests over 100,000 iterations took only a few seconds.) So you should still use generics because they are type-safe.

    I haven't been able to reproduce such performance benefits with generics compared to casting between reference types - so I'd say the performance gain is "supposed" more than "significant".

    0 讨论(0)
  • 2020-12-13 04:52

    In the case of generic collections vs. boxing et al, with older collections like ArrayList, generics are a performance win. But in the vast majority of cases this is not the most important benefit of generics. I think there are two things that are of much greater benefit:

    1. Type safety.
    2. Self documenting aka more readable.

    Generics promote type safety, forcing a more homogeneous collection. Imagine stumbling across a string when you expect an int. Ouch.

    Generic collections are also more self documenting. Consider the two collections below:

    ArrayList listOfNames = new ArrayList();
    List<NameType> listOfNames = new List<NameType>();
    

    Reading the first line you might think listOfNames is a list of strings. Wrong! It is actually storing objects of type NameType. The second example not only enforces that the type must be NameType (or a descendant), but the code is more readable. I know right away that I need to go find TypeName and learn how to use it just by looking at the code.

    I have seen a lot of these "does x perform better than y" questions on StackOverflow. The question here was very fair, and as it turns out generics are a win any way you skin the cat. But at the end of the day the point is to provide the user with something useful. Sure your application needs to be able to perform, but it also needs to not crash, and you need to be able to quickly respond to bugs and feature requests. I think you can see how these last two points tie in with the type safety and code readability of generic collections. If it were the opposite case, if ArrayList outperformed List<>, I would probably still take the List<> implementation unless the performance difference was significant.

    As far as performance goes (in general), I would be willing to bet that you will find the majority of your performance bottlenecks in these areas over the course of your career:

    1. Poor design of database or database queries (including indexing, etc),
    2. Poor memory management (forgetting to call dispose, deep stacks, holding onto objects too long, etc),
    3. Improper thread management (too many threads, not calling IO on a background thread in desktop apps, etc),
    4. Poor IO design.

    None of these are fixed with single-line solutions. We as programmers, engineers and geeks want to know all the cool little performance tricks. But it is important that we keep our eyes on the ball. I believe focusing on good design and programming practices in the four areas I mentioned above will further that cause far more than worrying about small performance gains.

    0 讨论(0)
提交回复
热议问题