Search code examples
sqlsqldatareaderdbdatareader

SqlDataReader / DbDataReader implementation question


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.


Solution

  • As stated here :

    Using the DataReader can increase application performance both by retrieving data as soon as it is available, and (by default) storing only one row at a time in memory, reducing system overhead.

    And as far as I know that's the way every reader works in the .NET framework.