Software development & .NET RSS 2.0
 Sunday, July 11, 2004

Last Friday I had a short discussion with a colleague on what the 'best' way was to get data out of the DataReader?

There are a number of options:

Use the name of the column:

SqlDataReader dr = cmd.ExecuteReader();

while{dr.Read())
{
...
string columnvalue  = dr["au_lname"].ToString();
...
}

The benefit here is the ease in writing the code and the readability.

 

The second way of approaching the DataReader is using an index:

while{dr.Read())
{
...
string columnvalue  = dr[1].ToString();
...
}

This code is a bit harder to read, but is should be faster because there's no need to do a lookup on the column-name.

Once an extra column is added to the query, we'll need to go over all of the indices to confirm we didn't break anything.

To verify that this code is actually faster, I created a small test-program that retrieves data from the pubs-database. The table shows the average time to get records from the authors-table into a variable.

count
----------

string
-----

index
-----

1

0.016766

 0.013735

10

0.002443

 0.001708

100

0.001064

0.000485

1000

0.000691

0.000383

10000

0.000697

0.000397

As you can see, it actually turns out to be faster to use an index.

To get the best of both worlds, you can use a combination of both approaches:

const int FIELD_AUID = 0;
const int FIELD_AU_LNAME = 1;
const int FIELD_AU_FNAME = 2;
...
while{dr.Read())
{
...
string columnvalue  = dr[FIELD_AU_LNAME].ToString();
...
}

This way changes to the query only require editing of the list of constants.

The performance gain for test-program seems to comparable to changing from the OleDbProvider to SqlClient. So making a small change to the code, has it running about twice as fast.

Sunday, July 11, 2004 4:11:21 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [0] -
Coding
Tracked by:
"penis enlargement pills" (penis enlargement pills) [Trackback]
"world cup odds" (world cup odds) [Trackback]
"slot machine gambling" (slot machine gambling) [Trackback]
"pet insurance" (pet insurance) [Trackback]
Archive
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2012
Alex Keizer
Sign In
Statistics
Total Posts: 86
This Year: 0
This Month: 0
This Week: 0
Comments: 71
Themes
Pick a theme:
All Content © 2012, Alex Keizer
DasBlog theme 'Business' created by Christoph De Baene (delarou)