使用“var”有多大影响?对C#编译器的性能有影响吗?
我发现 var
关键字极大地有助于减少 C# 代码中的噪音,而且可读性几乎没有损失;我想说,现在只有当编译器强制我时才使用显式类型。
我知道使用 var 不会改变我的代码的运行时特征。但我刚刚想到了一个问题:我是否在编译时为编译器现在代表我所做的所有额外工作付出了巨大的代价?
有没有人做过基准测试来看看广泛使用 var
对编译时间有多大影响?
I find the var
keyword greatly helps in reducing noise in my C# code, with little loss of readability; 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. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的建议:两种方法都尝试一下。测量结果。然后你就会知道了。
我没有做过任何基准测试,即使做了,也不能回答你的问题。我们不知道您有什么硬件,您的机器上还运行着什么,典型的程序是什么样的。我们也不知道您认为什么是可接受或不可接受的表现。你是唯一知道这一切的人,所以你是唯一能回答这个问题的人。
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.
正确答案是“没有什么可测量的”。有关 C# 编译器在编译时执行的部分(但很长)列表,请查看此处:
http://blogs.msdn.com/ericlippert/archive/2010/02/04/how-many-passes.aspx
然后明白类型推断只是该列表中单次传递的一部分。
The correct answer is "nothing measurable". For a partial (yet LONG) list of the passes the C# compiler makes while compiling, look here:
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.
无论如何都需要找到右侧的类型来进行类型检查和/或类型转换。将结果分配给变量的类型很便宜。大部分成本(如果有的话)将是在声明所有局部变量之前必须执行的操作以允许对表达式进行求值,但即使您不使用 var,您也要为此付出代价。 (顺便说一句,上述限制有可能甚至很可能根本不会损害性能。)
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. (BTW, it's possible or even likely that the above constraint doesn't hurt performance at all.)