SqlDataReader are these two the same Which one is faster

后端 未结 3 903
小蘑菇
小蘑菇 2021-01-20 00:45

I am working with SqlXml and the stored procedure that returns a xml rather than raw data. How does one actually read the data when returned is a xml and does not know about

3条回答
  •  执念已碎
    2021-01-20 01:12

    and have heard getting data from SqlDataReader through ordinal is faster than through column name

    Both your examples are getting data through the index (ordinal), not the column name:

    Getting data through the column name:

    while(reader.Read())
    {
        ...
        var value = reader["MyColumnName"];
        ...
    }
    

    is potentially slower than getting data through the index:

    int myColumnIndex = reader.GetOrdinal("MyColumnName");
    while(reader.Read())
    {
        ...
        var value = reader[myColumnIndex];
        ...
    }
    

    because the first example must repeatedly find the index corresponding to "MyColumnName". If you have a very large number of rows, the difference might even be noticeable.

    In most situations the difference won't be noticeable, so favour readability.

    UPDATE

    If you are really concerned about performance, an alternative to using ordinals is to use the DbEnumerator class as follows:

    foreach(IDataRecord record in new DbEnumerator(reader))
    {
        ...
        var value = record["MyColumnName"];
        ...
    }
    

    The DbEnumerator class reads the schema once, and maintains an internal HashTable that maps column names to ordinals, which can improve performance.

提交回复
热议问题