简体   繁体   English

使用'var'对C#编译器的性能有多大影响?

[英]How much impact does use of 'var' have on performance of C# Compiler?

I find the var keyword greatly helps in reducing noise in my C# code, with little loss of readability; 我发现var关键字在减少C#代码中的噪声方面有很大帮助,几乎没有可读性损失; I'd say that I now use explicit typing only when the compiler forces me to. 我会说我现在只在编译器强迫我使用时才使用显式输入。

I know that using var does not change the runtime characteristics of my code . 我知道使用var不会改变我的代码的运行时特性 But the question has just occurred to me: am I paying a big penalty at compile time for all the extra work that the compiler is now doing on my behalf? 但问题刚刚发生在我身上:我是否在编译时为编译器正在为我做的所有额外工作付出了巨大的代价?

Has anybody done any benchmarks to see how much difference extensive use of var makes to compilation times ? 有没有人做过任何基准测试,看看var大量使用对编译时间的影响有多大?

My advice: try it both ways. 我的建议:两种方式尝试。 Measure the results. 测量结果。 Then you'll know. 然后你就会知道。

I haven't done any benchmarks, and even if I had, that wouldn't answer the question for you. 我没有做任何基准,即使我有,也不会为你回答这个问题。 We do not know what hardware you have, what else is running on your machine, what a typical program looks like. 我们不知道你有什么硬件,你的机器上还有什么,一个典型的程序是什么样的。 Nor do we know what you consider to be acceptable or unacceptable performance. 我们也不知道您认为可接受或不可接受的表现。 You're the only one who knows all that, so you're the only one who can answer this question. 你是唯一知道这一切的人,所以你是唯一能回答这个问题的人。

The types need to be checked anyway, this may even save time... ok, unlikely :) 无论如何都需要检查类型,这甚至可以节省时间......好吧,不太可能:)
You shouldn't care though - if your development environment is slow, buy more memory or a new computer. 你不应该在意 - 如果您的开发环境很慢,请购买更多内存或新计算机。 Don't change the way you write code. 不要改变编写代码的方式。

The correct answer is "nothing measurable". 正确的答案是“没有可衡量的”。 For a partial (yet LONG) list of the passes the C# compiler makes while compiling, look here: 对于C#编译器在编译时所做的部分(但很长)的传递列表,请看这里:

http://blogs.msdn.com/ericlippert/archive/2010/02/04/how-many-passes.aspx http://blogs.msdn.com/ericlippert/archive/2010/02/04/how-many-passes.aspx

Then understand that the type inference is only part of a single pass on that list. 然后理解类型推断只是该列表上单个传递的一部分。

The type of the right hand side needs to be found anyway to do type checking and/or type conversion. 无论如何,需要找到右侧的类型来进行类型检查和/或类型转换。 Assigning the result to the variable's type is cheap. 将结果分配给变量的类型很便宜。 Most of the cost (if any) will be in what had to be done to allow the expression to be evaluated before all the local variables were declared but you pay for this even if you don't use var. 大多数成本(如果有的话)都是必须要做的,以便在声明所有局部变量之前允许对表达式进行求值,但即使你不使用var也要为此付出代价。 (BTW, it's possible or even likely that the above constraint doesn't hurt performance at all.) (顺便说一句,上述约束可能甚至可能不会损害性能。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM