Performance of anonymous types in C#

后端 未结 5 1721
傲寒
傲寒 2020-12-20 13:03

Is it bad to use anonymous types in C#?

相关标签:
5条回答
  • 2020-12-20 13:38

    An anonymous type in C# is still a static type and accessing its methods and properties is resolved by the compiler. The performance is comparable to explicit types.

    0 讨论(0)
  • 2020-12-20 13:48

    They're like other types, in terms of performance.

    edit

    To be more clear, I should have said that they perform exactly like other types because they are exactly like other types, except for the fact that the compiler generates the name. The only way performance would suffer is if you pass an instance of the anonymous type to another scope, where reflection or dynamic would have to be used just to access the properties. That would be expensive because it involves late binding to resolve everything at runtime.

    0 讨论(0)
  • 2020-12-20 13:54

    Are anonymous types in themselves bad? No. If they were the C# team certainly wouldn't have wasted their time adding it to the language. Under the hood they just compile down to standard CLR types.

    Can anonymous types, like practically every other language feature, be abused to the point of being non-performant. Sure.

    0 讨论(0)
  • 2020-12-20 13:56

    It's not bad, sometimes it is convinient. For example, when using Linq, instead of creating a class that will be used only once, it's preferable to use anonymous types.

    0 讨论(0)
  • 2020-12-20 13:59

    No, it is not. They are code generated classes at compiletime and perform as well as normal classes.

    0 讨论(0)
提交回复
热议问题