Do C# Generics Have a Performance Benefit?

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

    Not only can you do away with boxing but the generic implementations are somewhat faster than the non generic counterparts with reference types due to a change in the underlying implementation.

    The originals were designed with a particular extension model in mind. This model was never really used (and would have been a bad idea anyway) but the design decision forced a couple of methods to be virtual and thus uninlineable (based on the current and past JIT optimisations in this regard).

    This decision was rectified in the newer classes but cannot be altered in the older ones without it being a potential binary breaking change.

    In addition iteration via foreach on an List<> (rather than IList<>) is faster due to the ArrayList's Enumerator requiring a heap allocation. Admittedly this did lead to an obscure bug

提交回复
热议问题