开发者

Are anonymous types slower? [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Performance of anonymous types in C#

Are anonymous types slower than declarative types?

For example, does

Dim score as Double =开发者_开发技巧 CalculateScore()

run slower than

Dim score = CalculateScore()

?

Why use explicit typing if it's not slower?


An implicitly typed variable is "syntactic sugar". It gets compiled into exactly the same code either way, so runtime performance is unaffected.

Why use an explicit declaration?

It is a matter of style/preference/standard of a developer or organization. Some find the code to be more clear or intention-revealing.

For the record, an anonymous type (notice no double-n in there) is one that is declared inline, or "on-the-fly," depending on how you look at it. It is anonymous because it has no name. It is a temporary object that can be useful for holding related data.

In VB, it is declared by calling Dim anon = New With { .Name = "Moderator71", .Id = 19 } You can optionally declare some properties as Key.


No, there is no difference in speed for anonymous or inferred types.

But maybe you are talking about dynamic types, they would be a little slower.

Your (2nd) code sample suggests an inferred type, meaning score would be at compile-time determined to be a double


why use explicit typing?

Readability might be one.


Assuming that the CalculateScore Function returns a double.

No, it's the other way around. Declaring it As Double will always be as fast as is possible. Omitting the declaration will only be as fast when Option Infer On is in effect. If it is not then it will be a variable of type Object. The double will be boxed.

Unboxing is pretty expensive in VB.NET because it allows unboxing to any compatible type, not just Double. Unlike C# which throws an exception if there's a mismatch.


The reason to use explicit typing vs infered is because it moves a lot of bugs from run time to compile time. I can fix a compile time bug in seconds, thanks to the IDE. If a bug occurs in run time it might be months or even years before someone runs that particular line of code, or users might be hitting it every day but it might be a long time before it gets back to me and I can fix it. I call those time bombs. You don't know where or when they will go off.

My number 1 goal is to write code that doesn't blow up, so compile time bugs are awesome.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜