Should we use Generic Collection to improve safety and performance?

前端 未结 3 1698
滥情空心
滥情空心 2021-01-24 07:11

Should we use Generic Collection to improve safety and performance?

3条回答
  •  旧巷少年郎
    2021-01-24 07:19

    Of course. Why wouldn't you? More important than the performance, IMO, is the fact that generic APIs are more expressive. That goes for generic APIs in general, not just collections.

    EDIT: Just to clarify these a bit:

    • Performance characteristics are slightly different between the generic and nongeneric collections for reasons of "they're different implementation" as well as the whole generic/nongeneric side. Obviously the generic version avoids boxing/unboxing and (in most use cases) an execution time cast when fetching. In practice this is only likely to be significant for value types, where the boxing comes into play. For large collections, it's the difference in memory usage which is likely to be more significant than the execution speed difference.

    • I'm slightly less bothered by the actual type-safety aspect. It's certainly a good thing, but I can't remember ever actually seeing a bug when using the nongeneric collections due to putting the wrong type in (or fetching it as the wrong type). It's certainly a benefit though.

    • I view the expressiveness as very important. I can glance at the declaration of a method and know what to expect from the return value - I don't need to read the documentation quite as closely, or give variables quite as unwieldy names or docs. In addition you get all the benefits of Intellisense etc. One of the questions to ask about a language is "what can I express in it?" and generics allows much richer concepts to be expressed than before.

提交回复
热议问题