Will using 'var' affect performance?
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.
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.
Update 8 Years Later
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:
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 not exactly 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.
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.
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.
As Joel says, the compiler works out at compile-time what type var should be, effectively it's just a trick the compiler performs to save keystrokes, so for example
var s = "hi";
gets replaced by
string s = "hi";
by the compiler before any IL is generated. The Generated IL will be exactly the same as if you'd typed string.
As nobody has mentioned reflector yet...
If you compile the following C# code:
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!