关于SqlDataReader与SqlDataAdapter的比较,网上有很多。看的多了不难发现,都是人云亦云,且其中也不乏谬误之处。
给我感受最深的莫过于二者性能的描述:SqlDataReader是“只读访问 适合数据量较小",SqlDataAdapter"适于数据量较大时,要求资源也大一点"。甚至有赤裸裸的说“Reader要比Adapter速度快”,但事实到底如何呢(或许测试代码不专业,但是这个结果的确与我们从网上看到的描述反差很大.其实你去翻一翻MSDN,根本就没有只言片语关于这方面的描述,只能感叹人们的想象能力太丰富了).
测试的数据量(用的本机数据库)
测试代码如下
static void Main(string[] args)
{
var tempConnectionStr = "Data Source=.;Integrated Security=SSPI;Initial Catalog=xxxx;";
var tempCmdStr = "Select * from xxxx WHERE yyyy=0;";
var tempMax = 10;
SqlConnection tempCon = new SqlConnection(tempConnectionStr);
SqlCommand tempCmd = tempCon.CreateCommand();
tempCmd.CommandText = tempCmdStr;
switch (Console.ReadKey().KeyChar)
{
case '1':
Console.WriteLine();
for (int i = 0; i < tempMax; i++)
{
TestReader(10, tempCon, tempCmd);
}
break;
case '2':
Console.WriteLine();
for (int i = 0; i < tempMax; i++)
{
TestAdapter(10, tempCon, tempCmd);
}
break;
}
}
static void TestReader(int iMax, SqlConnection iCon, SqlCommand iCmd)
{
var tempSecond = 0L;
Stopwatch tempWatcher = new Stopwatch();
iCon.Open();
tempWatcher.Restart();
for (int i = 0; i < iMax; i++)
{
DataTable tempDt1 = new DataTable();
var tempReader = iCmd.ExecuteReader();
tempDt1.Load(tempReader);
}
tempWatcher.Stop();
tempSecond += tempWatcher.ElapsedMilliseconds;
iCon.Close();
Console.WriteLine("Total cost={0}, Avg cost={1}.", tempSecond, tempSecond / iMax);
}
static void TestAdapter(int iMax, SqlConnection iCon, SqlCommand iCmd)
{
var tempSecond = 0L;
Stopwatch tempWatcher = new Stopwatch();
iCon.Open();
tempWatcher.Restart();
for (int i = 0; i < iMax; i++)
{
DataTable tempDt1 = new DataTable();
SqlDataAdapter tempDa = new SqlDataAdapter(iCmd);
tempDa.Fill(tempDt1);
}
tempWatcher.Stop();
tempSecond += tempWatcher.ElapsedMilliseconds;
iCon.Close();
Console.WriteLine("Total cost={0}, Avg cost={1}.", tempSecond, tempSecond / iMax);
}
测试结果如下
使用SqlDataReader
使用SqlDataAdapter
如果把查询语句改为Select top 200 *,结果如下
使用SqlDataReader
使用SqlDataAdapter