SqlDataReader的是这两个相同的哪一个更快 [英] SqlDataReader are these two the same Which one is faster

查看:133
本文介绍了SqlDataReader的是这两个相同的哪一个更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正与SQLXML和存储过程返回一个XML,而不是原始数据。如何回到什么时候人真正​​读出的数据是XML,不知道列名。我用下面的版本,并听取了SqlDataReader的通过序得到的数据是不是通过列名快。请在这建议是最好的,有正当的理由或证据

  1. sqlDataReaderInstance.GetString(0)

  2. sqlDataReaderInstance [0];

解决方案
  

和听到从SqlDataReader的通过序得到的数据是不是通过列名

更快

你的两个例子都是通过指数(顺序)中获取数据,而不是列名:

通过列名获取数据:

 而(reader.Read())
{
    ...
    VAR值=读卡器[MyColumnName];
    ...
}
 

可能比通过索引获取数据较慢的:

  INT myColumnIndex = reader.GetOrdinal(MyColumnName);
而(reader.Read())
{
    ...
    VAR值=读卡器[myColumnIndex]
    ...
}
 

由于第一个例子中,必须反复找到对应于MyColumnName的指标。如果你有一个非常大的行数,差异甚至可能是明显的。

在大多数情况下,差异不会明显,所以有利于可读性。

更新

如果你真的关心性能,除了使用序号是使用的 DbEnumerator 类,如下所示:

 的foreach(在新DbEnumerator IDataRecord纪录(阅读器))
{
    ...
    VAR值=记录[MyColumnName];
    ...
}
 

DbEnumerator 类读取架构一次,并保持内部的哈希表列名映射到序数,从而提高性能。

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 the column names. I used the below versions and have heard getting data from SqlDataReader through ordinal is faster than through column name. Please advice on which is best and with a valid reason or proof

  1. sqlDataReaderInstance.GetString(0);

  2. sqlDataReaderInstance[0];

解决方案

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.

这篇关于SqlDataReader的是这两个相同的哪一个更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆