开发者

Is there a performance hit in using the 'var' keyword in C#? [duplicate]

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

Possible Duplicate:

C# ‘var’ vs specific type performance

I use the 'var' keyword extensively. A colleague told me there was a performance hit in using it, but couldnt back up his comment. Does anyone know of such a perfo开发者_StackOverflowrmance hit?


Someone asked that question on here already. In short, no, the IL code generated is the same. Therefore, no perf hit. If you ever wonder how one way of doing something differs from another, just write a sample and then use Reflector to analyze the differences.


No, var is just syntactical sugar. It doesn't actually get compiled into MSIL. Give a try compiling some code with the var keyword and without, then open the assembly in Reflector to see for yourself.


Since this is a compile-time feature, there could conceivably be slower compilation times, but not slower run-times.


This feature is called type inference. Compiler will infer the correct type at compile time and the msil generated will contain the correct type


Does he mean at compile time or at runtime?

At runtime, it is not possible to have a performance hit. The var keyword is handled entirely by the compiler, and it is completley impossible to tell from the IL whether the var keyword was used. Your friend might be thinking of C# 4's new dynamic keyword, which does have a performance impact.

At compile time, there might be a tiny performance impact, but it's nothing to worry about.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜