C# 使用“var”会影响性能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/356846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Will using 'var' affect performance?
提问by Jeff Keslinke
Earlier I asked a question about why I see so many examples use the var
keywordand got the answer that while it is only necessary for anonymous types, that it is used nonetheless to make writing code 'quicker'/easier and 'just because'.
早些时候我问了一个问题,为什么我看到这么多例子使用var
关键字,并得到了答案,虽然它只对匿名类型是必要的,但它仍然用于使编写代码“更快”/更容易和“只是因为”。
Following this link ("C# 3.0 - Var Isn't Objec")I saw that var
gets compiled down to the correct type in the IL (you will see it about midway down article).
在此链接(“C# 3.0 - Var 不是对象”)之后,我看到它var
在 IL中被编译为正确的类型(您将在文章中途看到它)。
My question is how much more, if any, IL code does using the var
keyword take, and would it be even close to having a measurable level on the performance of the code if it was used everywhere?
我的问题是使用var
关键字 take 的IL 代码还有多少(如果有的话),如果在任何地方都使用它,它是否甚至接近于对代码的性能具有可衡量的水平?
采纳答案by Joel Coehoorn
There's no extra IL code for the var
keyword: the resulting IL should be identical for non-anonymous types. If the compiler can't create that IL because it can't figure out what type you intended to use, you'll get a compiler error.
var
关键字没有额外的 IL 代码:对于非匿名类型,生成的 IL 应该是相同的。如果编译器无法创建该 IL,因为它无法确定您打算使用的类型,您将收到编译器错误。
The only trick is that var
will infer an exact type where you may have chosen an Interface or parent type if you were to set the type manually.
唯一的技巧是,var
如果您要手动设置类型,它将推断出您可能选择了接口或父类型的确切类型。
Update 8 Years Later
8 年后更新
I need to update this as my understanding has changed. I now believe it may be possible for var
to affect performance in the situation where a method returns an interface, but you would have used an exact type. For example, if you have this method:
由于我的理解发生了变化,我需要对此进行更新。我现在相信var
在方法返回接口的情况下可能会影响性能,但您会使用确切的类型。例如,如果你有这个方法:
IList<int> Foo()
{
return Enumerable.Range(0,10).ToList();
}
Consider these three lines of code to call the method:
考虑这三行代码来调用该方法:
List<int> bar1 = Foo();
IList<int> bar = Foo();
var bar3 = Foo();
All three compile and execute as expected. However, the first two lines are notexactly the same, and the third line will match the second, rather than the first. Because the signature of Foo()
is to return an IList<int>
, that is how the compiler will build the bar3
variable.
所有三个都按预期编译和执行。但是,前两行并不完全相同,第三行将匹配第二行,而不是第一行。因为 的签名Foo()
是返回一个IList<int>
,这就是编译器构建bar3
变量的方式。
From a performance standpoint, mostly you won't notice. However, there are situations where the performance of the third line may not be quite as fast as the performance of the first. As you continue to use the bar3
variable, the compiler may not be able to dispatch method calls the same way.
从性能的角度来看,大多数情况下您不会注意到。但是,在某些情况下,第三行的性能可能不如第一行的性能快。随着您继续使用该bar3
变量,编译器可能无法以相同的方式分派方法调用。
Note that it's possible (likely even) the jitter will be able to erase this difference, but it's not guaranteed. Generally, you should still consider var
to be a non-factor in terms of performance.It's certainly not at all like using a dynamic
variable. But to say it never makes a difference at all may be overstating it.
请注意,抖动有可能(甚至可能)能够消除这种差异,但不能保证。通常,您仍应var
将其视为性能方面的非因素。这当然完全不像使用dynamic
变量。但说它从来没有任何区别可能是夸大其词。
回答by Michael Burr
The C# compiler infers the true type of the var
variable at compile time. There's no difference in the generated IL.
C# 编译器var
在编译时推断变量的真实类型。生成的 IL 没有区别。
回答by ljs
As Joel says, the compiler works out at compile-timewhat type var should be, effectively it's just a trick the compiler performs to save keystrokes, so for example
正如乔尔所说,编译器在编译时计算出 var 应该是什么类型,实际上这只是编译器为保存击键而执行的一个技巧,例如
var s = "hi";
gets replaced by
被替换
string s = "hi";
by the compilerbefore any IL is generated. The Generated IL will be exactlythe same as if you'd typed string.
在生成任何 IL 之前由编译器执行。生成的 IL 将与您输入的字符串完全相同。
回答by ljs
If the compiler can do automatic type inferencing, then there wont be any issue with performance. Both of these will generate same code
如果编译器可以进行自动类型推断,那么性能就不会有任何问题。这两个将生成相同的代码
var x = new ClassA();
ClassA x = new ClassA();
however, if you are constructing the type dynamically (LINQ ...) then var
is your only question and there is other mechanism to compare to in order to say what is the penalty.
但是,如果您正在动态构建类型(LINQ ...),那么这var
是您唯一的问题,并且还有其他机制可以进行比较以说明惩罚是什么。
回答by jalf
I don't think you properly understood what you read. If it gets compiled to the correct type, then there isno difference. When I do this:
我认为您没有正确理解您所阅读的内容。如果它被编译为正确的类型,那么是没有什么区别。当我这样做时:
var i = 42;
The compiler knowsit's an int, and generate code as if I had written
编译器知道它是一个 int,并生成代码就像我写的一样
int i = 42;
As the post you linked to says, it gets compiledto the same type. It's not a runtime check or anything else requiring extra code. The compiler just figures out what the type must be, and uses that.
正如您链接到的帖子所说,它被编译为相同的类型。它不是运行时检查或其他任何需要额外代码的东西。编译器只是确定类型必须是什么,然后使用它。
回答by Brian Rudolph
There is no runtime performance cost to using var. Though, I would suspect there to be a compiling performance cost as the compiler needs to infer the type, though this will most likely be negligable.
使用 var 没有运行时性能成本。不过,我怀疑编译器需要推断类型会产生编译性能成本,尽管这很可能可以忽略不计。
回答by RichardOD
As nobody has mentioned reflector yet...
由于还没有人提到反射器......
If you compile the following C# code:
如果编译以下 C# 代码:
static void Main(string[] args)
{
var x = "hello";
string y = "hello again!";
Console.WriteLine(x);
Console.WriteLine(y);
}
Then use reflector on it, you get:
然后在上面使用反射器,你得到:
// Methods
private static void Main(string[] args)
{
string x = "hello";
string y = "hello again!";
Console.WriteLine(x);
Console.WriteLine(y);
}
So the answer is clearly no runtime performance hit!
所以答案显然是没有运行时性能下降!
回答by Rob
For the following method:
对于以下方法:
private static void StringVsVarILOutput()
{
var string1 = new String(new char[9]);
string string2 = new String(new char[9]);
}
The IL Output is this:
IL 输出是这样的:
{
.method private hidebysig static void StringVsVarILOutput() cil managed
// Code size 28 (0x1c)
.maxstack 2
.locals init ([0] string string1,
[1] string string2)
IL_0000: nop
IL_0001: ldc.i4.s 9
IL_0003: newarr [mscorlib]System.Char
IL_0008: newobj instance void [mscorlib]System.String::.ctor(char[])
IL_000d: stloc.0
IL_000e: ldc.i4.s 9
IL_0010: newarr [mscorlib]System.Char
IL_0015: newobj instance void [mscorlib]System.String::.ctor(char[])
IL_001a: stloc.1
IL_001b: ret
} // end of method Program::StringVsVarILOutput
回答by mjb
I always use the word var in web articles or guides writings.
我总是在网络文章或指南文章中使用 var 一词。
The width of the text editor of online article is small.
在线文章文本编辑器的宽度较小。
If I write this:
如果我这样写:
SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();
You will see that above rendered pre code text is too long and flows out of the box, it gets hidden. The reader needs to scroll to the right to see the complete syntax.
你会看到上面渲染的预代码文本太长并且开箱即用,它被隐藏了。读者需要向右滚动才能看到完整的语法。
That's why I always use the keyword var in web article writings.
这就是为什么我总是在网络文章写作中使用关键字 var。
var coolClass = new SomeCoolNameSpace.SomeCoolClassName.SomeCoolSubClassName();
The whole rendered pre code just fit within the screen.
整个渲染的预代码正好适合屏幕。
In practice, for declaring object, I seldom use var, I rely on intellisense to declare object faster.
在实践中,对于声明对象,我很少使用var,我依靠intellisense来更快地声明对象。
Example:
例子:
SomeCoolNamespace.SomeCoolObject coolObject = new SomeCoolNamespace.SomeCoolObject();
But, for returning object from a method, I use var to write code faster.
但是,为了从方法返回对象,我使用 var 来更快地编写代码。
Example:
例子:
var coolObject = GetCoolObject(param1, param2);
回答by ChrisH
So, to be clear, it's a lazy coding style. I prefer native types, given the choice; I'll take that extra bit of "noise" to ensure I'm writing and reading exactly what I think I am at code/debug time. * shrug *
所以,要清楚,这是一种懒惰的编码风格。如果有选择,我更喜欢原生类型;我会多加一点“噪音”,以确保我正在编写和阅读我在代码/调试时的想法。*耸耸肩*