Coding Efficient Data References

K

KNE

Is there someone out there willing to compare the performance differences
between different ways of refering to column data in a DataRow / DataColumn?

I've got a DataRow with several columns of different types. Something like:

DataRow dr = myTable.Rows;

with columns like:

dr["dbInteger"]
dr["dbCurrency"]
dr["dbVarChar"]
dr["dbChar"]
etc.

To assign one of the above to a value type variable, there are usually at
least two ways I can write each assignment.

Integer:

int i = (int)dr["myInteger"];
or
int i = Convert.ToInt32(dr["dbInteger"]);

String:

string myString = (string)dr["dbVarChar"];
or
string myString = dr["dbVarChar"].ToString();
or
string myString = Convert.ToString(dr["dbVarChar"]);

Do any or all of the above require unboxing? What is the most efficient way
of accessing / referencing the value in different types of DataColumns?

Thanks,

Ken
 
N

Neil McKechnie

Ken,

I believe that casting is faster than calling Convert.ToString or the
ToString() method of an object, as casting simply tells the compiler to take
what is supplied as the specified type.

The most efficient way to do what you want is to use a numeric index to
access the items in the data row, e.g.

string myString = dr.GetString(1);
or
string myString = (string) dr[1];

or you can use GetOrdinal outside of the row processing loop to find the
appropriate index of the item. Using the name of the column in the indexer
is always going to be slower than using the ordinal number.

Neil.
 
D

DarkSentinel

Thanks for the reply. What you have said seems to confirm some of my
own observations and conclusions.

To take this a bit further, would it hold true that using a strongly
typed dataset and using syntax like:

drObject.colName

would certainly be faster than:

drObject["colName"]

and possibly as fast as:

drObject[1]

?

Regards,

KNE
 

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