tags:

views:

84

answers:

2

i like to know difference retrieval from list using for (or) foreach loop and retrieval from list using linq query. specially in case of speed and other difference

EXample:

List A=new List() contains 10000 rows i need to copy filter some rows from list A which one better in case of speed am i go with for loop or linq query

+2  A: 

You could benchmark yourself and find out. (After all, only you know the particular circumstances in which you'll need to be running these loops and queries.)

My (very crude) rule-of-thumb -- which has so many caveats and exceptions as to be almost useless -- is that a for loop will generally be slightly faster than a foreach which will generally be slightly faster than a sensibly-written LINQ query.

You should use whatever construct makes the most sense for your particular situation. If what you want to do is best expressed with a for loop then do that; if it's best expressed as a foreach then do that; if it's best expressed as a query then use LINQ.

Only if and when you find that performance isn't good enough should you consider re-writing code that's expressive and correct into something faster and less expressive (but hopefully still correct).

LukeH
for loop faster then foreach? If you see number of operations performed, they all have exactly similar steps on compiled code which does not make any great difference while execution. Can you share more information about why and how for will be faster then foreach?
Akash Kava
@Akash: In general `foreach` instantiates and uses an enumerator behind-the-scenes whereas `for` uses direct, indexed access. (Although I think the compiler optimises `foreach` into a `for` for certain types - arrays and strings, off the top of my head.) But, as I said in my answer, you should use whichever construct best expresses your intent rather than worrying about these minutiae.
LukeH
@akash - to reiterate, the JIT can avoid bounds-checking on "for" loops over an array *in some cases*. in general though they are close enough that it is a non-issue.
Marc Gravell
@LukeH, for array types foreach gets converted to for and for non array like list etc, indexed access anyway checks for out of bound exceptions in each list etc types, i dont think there is any difference at all except using one more enumerator object instance.
Akash Kava
@Akash: *And that is a difference* - usually a very small difference, and usually not worth worrying about, but a difference nevertheless.
LukeH
+1  A: 

If we're talking regular LINQ, then we're focusing on IEnumerable<T> (LINQ-to-Objects) and IQueryable<T> (LINQ-to-most-other-stuff). Since IQueryable<T> : IEnumerable<T>, it is automatic that you can use foreach - but what this means is very query-specific, since LINQ is generally lazily spooling data from an underlying source. Indeed, that source can be infinite:

public IEnumerable<int> Forever() {
    int i = 0;
    while(true) yield return i++;
}
...
foreach(int i in Forever()) {
    Console.WriteLine(i);
    if(Console.ReadLine() == "exit") break;
}

However, a for loop requires the length and an indexer. Which in real terms, typically means calling ToList() or ToArray():

var list = source.ToList();
for(int i = 0 ; i < list.Count ; i++) { do something with list[i] }

This is interesting in various ways: firstly, it will die for infinite sequences ;p. However, it also moves the spooling earlier. So if we are reading from an external data source, the for/foreach loop over the list will be quicker, but simply because we've moved a lot of work to ToList() (or ToArray(), etc).

Another important feature of performing the ToList() earlier is that you have closed the reader. You might need to operate on data inside the list, and that isn't always possible while a reader is open; iterators break while enumerating, for example - or perhaps more notably, unless you use "MARS" SQL Server only allows one reader per connection. As a counterpoint, that reeks of "n+1", so watch for that too.

Over a local list/array/etc, is is largely redundant which loop strategy you use.

Marc Gravell