Do C# Generics Have a Performance Benefit?

19,795

Solution 1

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.

Solution 2

Not only yes, but HECK YES. I didn't believe how big of a difference they could make. We did testing in VistaDB after a rewrite of a small percentage of core code that used ArrayLists and HashTables over to generics. 250% or more was the speed improvement.

Read my blog about the testing we did on generics vs weak type collections. The results blew our mind.

I have started rewriting lots of old code that used the weakly typed collections into strongly typed ones. One of my biggest grips with the ADO.NET interface is that they don't expose more strongly typed ways of getting data in and out. The casting time from an object and back is an absolute killer in high volume applications.

Another side effect of strongly typing is that you often will find weakly typed reference problems in your code. We found that through implementing structs in some cases to avoid putting pressure on the GC we could further speed up our code. Combine this with strongly typing for your best speed increase.

Sometimes you have to use weakly typed interfaces within the dot net runtime. Whenever possible though look for ways to stay strongly typed. It really does make a huge difference in performance for non trivial applications.

Solution 3

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.

Solution 4

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.

Solution 5

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. :-)

Share:
19,795
Roberto Bonini
Author by

Roberto Bonini

I have graduated from the University of the West of Scotland with a 2:1 degree in Computer Science (Honors). I enjoy programming and problem solving. I work with Visual Studio 2010, and use Netbeans for my Java work. My Honours Year thesis was cloud computing and Windows Azure in particular. A lot of my workd since has involved Windows Azure. I mainly program in C#@rbonini

Updated on June 02, 2022

Comments

  • Roberto Bonini
    Roberto Bonini almost 2 years

    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, or writing a separate class to deal with each data class?

    Is there a performance benefit or any other benefit (other than it saving me the time of writing separate classes)?

  • ShuggyCoUk
    ShuggyCoUk over 15 years
    bonus for the obscure skeet reference ;)
  • codeulike
    codeulike almost 15 years
    I was just reading Tony Northrup's book, that exact page, and ended up here after googling about the performance benefits of generics. The answers to this question seem wildly different - You and Tony both find there is little performance benefit, while others (e.g. Jason Short, above) find a massive performance benefit. I wonder why there is so much difference here?
  • JohnIdol
    JohnIdol almost 15 years
    keep in mind I am not talking about primitives (boxing/unboxing), that is obviously faster with genercis - Microsoft claims that Generics provide better performance than casting between reference types but I am getting quite the opposite result! Have a look at the comments here dotnetbutchering.blogspot.com/2008/09/… (my blog) and you'll find my results
  • vpalmu
    vpalmu over 14 years
    Which I have done, but my hand-rolled was also generic so go figure.
  • Captain Sensible
    Captain Sensible about 14 years
    Empirical evidence tells me that the supposed performance benefit of using generics is largely theoretical. Strong typing however is a pretty convincing argument to choose generics over their non-generic counterparts.
  • Steven
    Steven almost 13 years
    Without seeing the actual code that Tony used to test, it's hard to argue about this. It is possible that Tony compared built-in generic types (such as List<string>) with a non-generic equivalent (such as StringCollection) and this comparison does not say much about the performance of generics itself, but rather compares the performance of those two implementations. Casting is quite an expensive operation, so you would normally see a performance improvement when using a generic type (that saves you from casting) over a non-generic type and having to cast constantly.
  • Steven
    Steven almost 13 years
    You are referring to MCTS 70-536 aren't you? This is by far the worst computer related book I've read in my career (and I've read quite a few). Not only is it full of silly mistakes and it contains many statements that are plain wrong. Even the published errata list just covers about 10% of the actual errors in the book.
  • Mitkins
    Mitkins almost 12 years
    It's fairly easy to test this for yourself. In response to one of the other answers on this question, I wrote a test program (loop adding an item to the list, then reading the just-added item), and I found that List<string> is consistently about 40% faster than ArrayList, no matter how many things are added. I tried with 10, 100, 1000, 1000000 and 100 million, and it's always the same speed benefit for generics...