views:

2693

answers:

6

Which is generally fastest when reading/comparing row info from a DataTable?

'assume dt as datatable'

'method 1'
dim i as int32
for i = 0 to dt.rows.count - 1
   ....
next

'method 2'
dim row as datarow
for each row in dt.rows
    ....
next

And if there's a difference, in what circumstances does it pay to use one over the other?

Thanks in advance for any guidance!

+2  A: 

In reality no difference. Although you technically pay a small price in the foreach method, for going through the IEnumerable interface.

Greg Dean
Yes, in my test harness the two methods only show a performance difference after about 100K iterations.
StingyJack
+3  A: 

The second would have a slight penalty. However as for circumstances, I persoanlly would always use method 2 for clarity of code. However, I would use method 1 if I ever need to do something such as accessing a next/previous row while analyzing the current row.

mattlant
A: 

@gdean232 is right - almost no difference at all. If performance is an issue, using a a SqlDataReader instead is noticeable faster.

Mike
+2  A: 

The compiler expands For Each to a short while loop.

for each row in dt.rows
// expands to:
IEnumerator e = dt.rows.GetEnumerator()
while e.MoveNext()
    row = e.Current

So you pay a small amount of overhead. But for clarities sake, I'd still stick with For Each if you're only working on one row, and you aren't modifying the data set.

Matthew Scharley
A: 

The foreach implementation is actually slightly faster than the standard for implementation, because each index array access needs to be bounds checked. However, since the idiom:

for(int i =0; i < myArray.Count; ++i)
{
    // do something with myArray[i];
}

is common, the compiler looks for it as a special case and optimizes it, so it becomes faster. However, any small deviation from that format (such as int len = MyArray.Count; for(int i =0; i< len; ++i)) won't be recognized, and will use the slower code.

James Curran
+2  A: 

Well, there is a difference, since GetEnumerator and MoveNext that get called in foreach-loop are virtual (calling requires going through a pointer) and thus can't be inlined. This overhead in reality is small, unless you do a lot of loops.

In some cases though the compiler will replace foreach with a for-loop (I believe when iterating over arrays).

I personally prefer foreach in my ASP.NET MVC code for clarity, as many have said here, but often use the for-loop too. Joe Duffy recently posted an interesting article about the cost of enumerating http://www.bluebytesoftware.com/blog/2008/09/21/TheCostOfEnumeratingInNET.aspx

liggett78