我有一个存储过程,它返回Microsoft Adventure Works数据库中的Address表中的前1000条记录。我写了几个单元测试来比较Dapper和使用普通的ADO.net。测试结果让我感到困惑。
ADO.net测试平均需要79.6毫秒。 Dappers需要33.3ms。我使用ADO.net错了吗?有没有更快的方法从我的存储过程结果创建模型?为什么它比Dappers扩展方法慢两倍?
ADO.Net测试
public async Task Performance_test_query_using_straight_ado()
{
var watch = new Stopwatch();
var times = new List<double>();
var sales = new List<AddressFixture>();
int upperLimit = 500;
for (int count = 0; count < upperLimit; count++)
{
watch.Start();
var sqlConnection = new SqlConnection("ConnectionString");
await sqlConnection.OpenAsync();
var sqlCommand = new SqlCommand("GetAllAddresses", sqlConnection);
sqlCommand.CommandType = CommandType.StoredProcedure;
var reader = sqlCommand.ExecuteReader();
var results = new List<AddressFixture>();
while (reader.Read())
{
results.Add(new AddressFixture
{
AddressLine1 = reader["AddressLine1"].ToString(),
AddressLine2 = reader["AddressLine2"].ToString(),
City = reader["City"].ToString(),
ModifiedDate = Convert.ToDateTime(reader["ModifiedDate"]),
PostalCode = reader["PostalCode"].ToString(),
StateProvinceId = (int)reader["StateProvinceId"],
});
}
watch.Stop();
// We don't include the first query as it includes Unit Test framework delays.
if (count == 0)
{
watch.Reset();
continue;
}
times.Add(watch.Elapsed.TotalMilliseconds);
sales.AddRange(results);
Debug.WriteLine("Queried {0} items in {1}ms", results.Count(), watch.Elapsed.TotalMilliseconds);
watch.Reset();
}
Debug.WriteLine("");
Debug.WriteLine(string.Format("Average time to query, using an average over {0} queries: {1}ms", upperLimit, times.Sum() / times.Count));
Debug.WriteLine(string.Format("Total items returned over {0} queries: {1}", upperLimit, sales.Count));
Debug.WriteLine(string.Format("Total time to query all {0} times: {1}ms", upperLimit, times.Sum()));
}
Dapper测试
public async Task Performance_test_query_using_dapper_ado_extension()
{
var watch = new Stopwatch();
var times = new List<double>();
var sales = new List<AddressFixture>();
int upperLimit = 500;
for (int count = 0; count < upperLimit; count++)
{
watch.Start();
var sqlConnection = new SqlConnection("ConnectionString");
var results = await sqlConnection.QueryAsync<AddressFixture>(
new CommandDefinition("GetAllAddresses"));
watch.Stop();
// We don't include the first query as it includes Unit Test framework delays.
if (count == 0)
{
watch.Reset();
continue;
}
times.Add(watch.Elapsed.TotalMilliseconds);
sales.AddRange(results);
Debug.WriteLine("Queried {0} items in {1}ms", results.Count(), watch.Elapsed.TotalMilliseconds);
watch.Reset();
}
Debug.WriteLine("");
Debug.WriteLine(string.Format("Average time to query, using an average over {0} queries: {1}ms", upperLimit, times.Sum() / times.Count));
Debug.WriteLine(string.Format("Total items returned over {0} queries: {1}", upperLimit, sales.Count));
Debug.WriteLine(string.Format("Total time to query all {0} times: {1}ms", upperLimit, times.Sum()));
}
更新
我注意到我没有关闭连接。完成此操作后,测试时间降至39.3ms。它仍然比Dapper慢6ms,当我认为它应该更快。