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();
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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"]

1 Comment

How does this answer if the int or the string indexer is more efficient?
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.