How much impact does use of 'var' have on performance of C# Compiler?

Viewed 2848

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?

4 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.

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.

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.)

Related