foreach Vs. dt.Select

B

Ben

Hi all,

I need to update an particular set of rows in a datatable.
Here is some sample code of what I want to do:

DataTable dt = (DataTable)Session["Table"];
foreach(DataRow dr in dt.Rows)
{
if(dr.RowState == DataRowState.Added)
//Do something
}

Instead, I could also do:
DataRow[] dr = dt.Select("","",DataViewRowState.Added);
if(dr.Length > 0)
{
for(int i = 0; i < dr.Length; i++)
{
DataRow drCurrent = dr;
//Do Something
}
}


My question is: Is there a significant performance difference between
the two approaches? The datatable should only have a few records
(maximum 10).

Thanks in advance,
Ben
 
P

Peter Duniho

[...]
My question is: Is there a significant performance difference between
the two approaches? The datatable should only have a few records
(maximum 10).

Without even knowing anything specific about the implementation of
Select(), I cannot imagine that there's a significant difference between
the two approaches when the table has only ten rows at most.

That said, this is something that should be easy enough for you to verify
yourself. Even without formal profiling tools, just use the Stopwatch
class to measure the time each implementation takes and compare the two
directly that way.

By the way, the "if (dr.Length > 0)" is pointless. The for() loop will do
that check implicitly, since 0 (the initial value of i) is not less than 0.

Also, foreach() and Select() are not mutually exclusive. Even if there
was some performance advantage to using Select(), you could still
enumerate the results with foreach() rather than using an explicit loop
variable. IMHO, using foreach() is preferable when it's an option.

Pete
 
C

Cor Ligthert[MVP]

For sure is the select slower, the select uses an expression which has first
to be translated.

The enumurating through the property rows is for sure as fast as the doing
the same through the collection of rows (although it are probably less
rows). As Peter already wrote, you have to investigate the result of the
select first because it can return null. And then you loose even more time.

We are talking probably about thousands of picoseconds

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top