Jeff Keslinke Jeff Keslinke - 1 year ago 71
C# Question

Will using 'var' affect performance?

Earlier I asked a question about why I see so many examples use the

keyword and 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'.

Following this link ("C# 3.0 - Var Isn't Objec") I saw that
gets compiled down to the correct type in the IL (you will see it about midway down article).

My question is how much more, if any, IL code does using the
keyword take, and would it be even close to having a measurable level on the performance of the code if it was used everywhere?

Answer Source

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 effect 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. It's possible (likely even) the jitter will be able to erase this difference, but it's not guaranteed.

Generally, though, you should still consider var to be a non-factor in terms of performance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download