Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C# Generics Have a Performance Benefit?

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)?

like image 218
Roberto Bonini Avatar asked Sep 22 '08 19:09

Roberto Bonini


People also ask

What is do in C programming?

The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false.

Do while loop examples in C?

Example 2: do...while loop The condition is checked only after the first iteration has been executed. do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0);

Do loops syntax?

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.


2 Answers

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.

like image 68
Danimal Avatar answered Sep 22 '22 18:09

Danimal


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.

like image 20
Jason Short Avatar answered Sep 23 '22 18:09

Jason Short