0

In C#, which one is more efficient way of reading reader object, through integer indexes or through named indexes ?

ad.Name = reader.GetString(0);

OR

ad.Name = reader["Name"].ToString();
Ali Shahzad
  • 5,163
  • 7
  • 36
  • 64

3 Answers3

3

The name overload needs to find the index first.

MSDN

a case-sensitive lookup is performed first. If it fails, a second case-insensitive search is made (a case-insensitive comparison is done using the database collation). Unexpected results can occur when comparisons are affected by culture-specific casing rules. For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter 'i' in "file".

From Getordinal (which is used therefore):

Because ordinal-based lookups are more efficient than named lookups, it is inefficient to call GetOrdinal within a loop. Save time by calling GetOrdinal once and assigning the results to an integer variable for use within the loop.

so in a loop it might be more efficient to lookup the ordinal index once and reuse that in the loop body.

However, the name-lookup is backed by a class that is using a HashTable which is very efficient.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0
ad.Name = reader["Name"].ToString();

This is most efficient way.

Because although you change database table structure afterwords, there will be no effect on this code since you have directly mentioned column name.

But with column index, it will change when you add any column to table before this column.

C Sharper
  • 8,284
  • 26
  • 88
  • 151
  • 2
    This might be more readable and less error-prone, but it's not as efficient since it needs to find the ordinal first. If you do that in a loop millions of times it would be more _efficient_ to put it above the loop. – Tim Schmelter Oct 29 '13 at 08:23
0

reader.GetString(index);

This will get the row value at that column index as string, The second solution is more ideal because it allows you to get the value at that index in your own prefered type.

Example:-

String name = reader["Name"].ToString();
int age = (int) reader["Age"]