SqlDataReader / DbDataReader 实现问题
有谁知道 DbDataReaders 实际上是如何工作的。我们可以使用SqlDataReader作为例子。
当您执行以下操作时,
cmd.CommandText = "SELECT * FROM Customers";
var rdr = cmd.ExecuteReader();
while(rdr.Read())
{
//Do something
}
数据读取器是否在内存中拥有所有行,还是只抓取一行,然后当调用 Read 时,它是否会转到数据库并抓取下一行?似乎只将一个放入内存会导致性能不佳,但将所有这些放入内存会使调用 ExecuteReader 花费一些时间。
我知道我是该对象的使用者,他们如何实现它并不重要,但我只是好奇,我想我可能会在 Reflector 上花几个小时来了解它在做什么,所以我想问一下可能知道的人。
我只是好奇是否有人有想法。
Does anyone know how DbDataReaders actually work. We can use SqlDataReader as an example.
When you do the following
cmd.CommandText = "SELECT * FROM Customers";
var rdr = cmd.ExecuteReader();
while(rdr.Read())
{
//Do something
}
Does the data reader have all of the rows in memory, or does it just grab one, and then when Read is called, does it go to the db and grab the next one? It seems just bringing one into memory would be bad performance, but bringing all of them would make it take a while on the call to ExecuteReader.
I know I'm the consumer of the object and it doesn't really matter how they implement it, but I'm just curious, and I think that I would probably spend a couple hours in Reflector to get an idea of what it's doing, so thought I'd ask someone that might know.
I'm just curious if anyone has an idea.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如此处所述:
据我所知,这就是每个读者在 .NET 框架中工作的方式。
As stated here :
And as far as I know that's the way every reader works in the .NET framework.
狂想曲是正确的。
与 DataAdaptor 进行了测试,发现 DataAdaptor 始终比 DataReader 快 3-4 毫秒,但 DataAdaptor 最终会占用更多内存。
当我对相同的 50,000 个记录数据集运行相同的测试时,我发现 DataReader 端的性能提高了 50 毫秒。
话虽如此,如果您有一个长时间运行的查询或一个巨大的结果集,我认为使用 DataReader 可能会更好,因为您可以更快地获得结果,并且不必将所有数据保留在内存中。同样重要的是要记住,DataReader 只能向前移动,因此如果您需要在结果集中移动,那么它不是最佳选择。
Rhapsody is correct.
I ran a test using DataReaders vs DataAdaptors on an equal 10,000 record data set, and I found that the DataAdaptor was consistently 3-4 milliseconds faster than the DataReader, but the DataAdaptor will end up holding onto more memory.
When I ran the same test on equal 50,000 record data sets I saw a performance gain on the DataReader side to the tune of 50 milliseconds.
With that said, if you had a long running query or a huge result set, I think you may be better off with a DataReader since you get your results sooner and don't have to hold onto all of that data in memory. It is also important to keep in mind that a DataReader is forward only, so if you need to move around in your results set, then it is not the best choice.