SqlDataReader vs SqlDataAdapter: which one has the better performance for returning a DataTable?

蓝咒 提交于 2019-11-29 22:20:35

The difference will be negligible, so it's probably better to use the more concise version: SqlDataAdapter.Fill.

SqlDataReader.Fill creates an internal class LoadAdapter (derived from DataAdapter) internally, and calls its Fill method: performance will be very similar to SqlDataAdapter.Fill(DataTable).

There will be some small differences in initialization / validation of arguments, but as the number of rows increases, this will become less and less significant.

Note also that your second sample should be modified to be comparable with the first:

public DataTable populateUsingDataAdapter(string myQuery)
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        SqlDataAdapter dap = new SqlDataAdapter(myQuery,con);
        DataTable dt = new DataTable();
        dap.Fill(dt);
        return dt;
    }
}
Tim Medora

This question, and more specifically, this answer suggests that your second example is faster. It is certainly not an exhaustive benchmark but it is an interesting test.

Reflecting the source code of DataTable shows that calling DataTable.Load() actually creates an internal DataAdapter subclass called LoadAdapter and calls the Fill() method of DataAdapter. SqlDataAdapter does the bulk of its loading work in the exact same place.

More importantly, I would tend to favor the second example for readability. Neither example compares to the fast access provided by direct use of the DataReader, so I would opt for the cleaner code.

SqlDataReader has historically been significantly faster than SqlDataAdapter. Improvements may have been made in .NET 4.5, but I doubt it has improved enough to outpace the performance of the DataReader.

SqlDataReader will be faster than SQlDataAdapter because it works in a connected state which means the first result is returned from query as soon as its available ..

In addition to the selected solution, I would like to add that:

Using the DataReader, you don´t need to know which type of DbConnection you have.

All you need is an instance which implements IDbConnection, with that you can use "connection.CreateCommand" and then "dbCommand.ExecuteReader" and then dataTable.Load.

But when you use DataAdapter you will need to know which connection is used (i.e. oracle, sqlserver, etc.)

(It´s not relevant for the thread starter, but I landed here using g**gle while looking for this topic.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!