Do C# Generics Have a Performance Benefit?

前端 未结 12 1132
感动是毒
感动是毒 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:32

    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.

提交回复
热议问题