I want to know which one has the better performance for returning a DataTable
. Here for SqlDataReader
I use DataTable.Load(dr)
Using SqlDataReader
:
public static DataTable populateUsingDataReader(string myQuery) { DataTable dt = new DataTable(); using (SqlConnection con = new SqlConnection(constring)) { SqlCommand cmd = new SqlCommand(myQuery, con); con.Open(); SqlDataReader dr = null; dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (dr.HasRows) { dt.Load(dr); } return dt; } }
using SqlDataAdapter
:
public DataTable populateUsingDataAdapter(string myQuery) { SqlDataAdapter dap = new SqlDataAdapter(myQuery,cn); DataSet ds = new DataSet(); dap.Fill(ds); return ds.Tables[0]; }
Caching namespace. If you're doing purely data operations (as your question suggests), you could rewrite your code which is using the data to be T-SQL and run natively on SQL. This has the potential to be much faster, as you will be working with the data directly and not shifting it about.
The DataSet represents a complete set of data among the tables that include related tables, constraints, and relationships. However, this greater functionality comes with performance overhead; therefore, DataSet is slower than DataReader.
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. A DataAdapter is used to retrieve data from a data source and populate tables within a DataSet.
SqlAdapter is used to fill a dataset. SqlCommand can be used for any purpose you have in mind related to Create/Read/Update/Delete operations, stored procedure execution and much more.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With