IEnumerable or var [duplicate]
Possible Duplicate:
C# 'var' vs specific type performance
In term of performance does it make any difference to use var or IEnumerable in linq? what about IEnumerable or IQueryable? how can we know which one is IEnumerable and which one is IQueryable? for ex: in code below
IEnumerable<CaseTable> test开发者_开发知识库 = from x in dataBase.CaseTables
where x.case_id.Equals("12")
select x;
It will make a difference if the return type isn't the same, and this then changes composition. For example:
IEnumerable<Users> users = db.Users;
var count = users.Count();
versus:
var users = db.Users;
var count = users.Count();
If this is actually a DB provider, the second should issue a "select COUNT(1) from Users" (1 row, 1 column) - however, the first will issue a "select * from Users" - n columns times m rows. It will drag the data over the network, materialise it into objects, and then (LINQ-to-Objects) count the objects.
If it was already IEnumerable<T>
then it will make no difference.
Re knowing what it is - hover ;) or better: use a profiler (such as mvc-mini-profiler) so that you can keep a close eye on the queries it is running at all times.
var is only syntax for the programmer - it doesn't change the semantics at all. If you declared as var
, the type of test is still IEnumerable<CaseTable>
in your example.
As for whether it's IEnumerable or IQueryable - that depends on the type of dataBase.CaseTables
Using var
instead of IEnumerable<T>
can make a performance difference in the case when the type of the expression on the right side is not IEnumerable<T>
.
In your code above (assuming dataBase.CaseTables
is IQueryable<CaseTable>
backed by LINQ to SQL or some similar provider), if you wrote test.First()
, you could retrieve lots of rows from the database to get only the first one.
If you used var
or IQueryable<CaseTable>
, you would retrieve only the first row.
This can make difference even without IQueryable<T>
. For example, List<T>.GetEnumerator()
returns a custom struct
. Iterating using that is going to be faster than iterating through IEnumerator<T>
. Although the difference is going to be negligible most of the time.
What this all means: yes, using var
can make a difference: it can make your code faster, in some cases much faster.
The keyword "var" is just syntactic sugar in C#. The variable declared by that is still statically typed, and the compiler will infer its type.
Type obj = new Type() and var obj = new Type() are the same.
"var" is usefull to make your code less bloated when the type of the variable is evident from its declaration. It's also very nice when you want to discover the not-so-obvious type of a variable (via IntelliSense) - "LINQ" rings some bells.
Of course, restrictions apply to when you can use 'var'. Have a look here.
精彩评论