Reputation: 4295
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!
Upvotes: 0
Views: 17179
Reputation: 11358
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://joeduffyblog.com/2008/09/21/the-cost-of-enumerating-in-net/
Upvotes: 3
Reputation: 103605
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.
Upvotes: -2
Reputation: 132534
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.
Upvotes: 8
Reputation: 2003
@gdean232 is right - almost no difference at all. If performance is an issue, using a a SqlDataReader instead is noticeable faster.
Upvotes: 1
Reputation: 15451
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.
Upvotes: 3
Reputation: 30117
In reality no difference. Although you technically pay a small price in the foreach method, for going through the IEnumerable interface.
Upvotes: 3