Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using var actually slow? If so, why?

Tags:

c#

var

I am learning C# and .NET, and I frequently use the keyword var in my code. I got the idea from Eric Lippert and I like how it increases my code's maintainability.

I am wondering, though... much has been written in blogs about slow heap-located refs, yet I am not observing this myself. Is this actually slow? I am referring to slow compile times due to type inferencing.

like image 397
PRASHANT P Avatar asked Nov 27 '22 22:11

PRASHANT P


2 Answers

You state:

I am referring to slow time for compile due to type 'inferencing'

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. In some ways using this already-known type removes a few things (the potential to have to check for inheritance, interfaces and conversion operators, for example).

It also doesn't slow down the runtime; they are fully static compiled like regular c# variables (which they are).

In short... it doesn't.

like image 127
Marc Gravell Avatar answered Nov 29 '22 11:11

Marc Gravell


'var' in C# is not a VARIANT like you're used to in VB. var is simply syntactic sugar the compiler lets you use to shorthand the type. The compiler figures out the type of the right-hand side of the expression and sets your variable to that type. It has no performance impact at all - just the same as if you'd typed the full type expression:

var x = new X();

exactly the same as

X x = new X();

This seems like a trivial example, and it is. This really shines when the expression is much more complex or even 'unexpressable' (like anonymous types) and enumerables.

like image 22
n8wrl Avatar answered Nov 29 '22 12:11

n8wrl