Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 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?

like image 378
Samuel Jack Avatar asked Feb 18 '10 10:02

Samuel Jack


People also ask

Does var affect performance?

There is no runtime performance cost to using var.

Does using var slow down C#?

This does not slow down the compiler. The compiler already has to know the result type of the expression, in order to check compatibility (direct or indirect) of the assignment.

Is it good practice to use var in C#?

It is recommended to use var only when it is necessary, that is, when the variable will be used to store an anonymous type or a collection of anonymous types. The complaint that var reduces readability is not shared by everyone.

What does VAR do in C?

var is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration.


1 Answers

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.

like image 55
Eric Lippert Avatar answered Sep 22 '22 18:09

Eric Lippert