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

后端 未结 5 1837
陌清茗
陌清茗 2020-12-24 03:12

I want to know which one has the better performance for returning a DataTable. Here for SqlDataReader I use DataTable.Load(dr)

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-24 03:54

    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;
        }
    }
    

提交回复
热议问题