C# – SqlDataReader performance differences in accessing values

asp.netcsqldatareader

When accessing values from an SqlDataReader is there a performance difference between these two:

string key = reader.GetString("Key");

or

string key = reader["Key"].ToString();

In this code sample:

string key;

using (SqlDataReader reader = cmd.ExecuteReader())
{
    while (reader.Read())
    {
        key = reader.GetString("Key");
        // or
        key = reader["Key"].ToString();
    }
}

Best Answer

I’ve just peeked into the .NET source code, and the two access methods are essentially the same. The only difference is that the second does an additional boxing. So the first one corresponds to something like (in case of elementary types):

int key = GetInternalSQLDataAsInt32("Key");

while the second one would be:

int key = (int)(object)GetInternalSQLDataAsInt32("Key");

The GetInternalSQLDataAsInt32(...) function represents the SQL data library machinery of marshalling data from SQL to .NET.

But as pointed above, a more significant difference can be expected between string-based keys and ordinal-based keys.