最佳答案
我试图确定实体框架比存储过程慢多少。我希望说服我的老板让我们使用实体框架来简化开发。
问题是我运行了一个性能测试,看起来 EF 比存储处理器慢7倍。我觉得这太难以置信了我在想我是不是遗漏了什么。这是一个决定性的测试吗?我能做些什么来提高 EF 测试的成绩呢?
var queries = 10000;
// Stored Proc Test
Stopwatch spStopwatch = new Stopwatch();
spStopwatch.Start();
for (int i = 0; i < queries; i++ )
{
using (var sqlConn = new SlxDbConnection().Connection)
{
var cmd = new SqlCommand("uspSearchPerformanceTest", sqlConn) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("@searchText", "gstrader");
sqlConn.Open();
SqlDataReader dr = cmd.ExecuteReader();
List<User> users = new List<User>();
while (dr.Read())
{
users.Add(new User
{
IsAnonymous = Convert.ToBoolean(dr["IsAnonymous"]),
LastActivityDate = Convert.ToDateTime(dr["LastActivityDate"]),
LoweredUserName = dr["LoweredUserName"].ToString(),
MobileAlias = dr["MobileAlias"].ToString(),
UserId = new Guid(dr["UserId"].ToString()),
UserName = (dr["UserName"]).ToString()
});
}
var username = users.First().UserName;
sqlConn.Close();
}
}
spStopwatch.Stop();
Console.WriteLine("SP - {0} Queries took {1}", queries, spStopwatch.ElapsedMilliseconds );
// EF Test
Stopwatch entityStopWatch = new Stopwatch();
var context = new SlxDbContext();
var userSet = context.Set<User>();
entityStopWatch.Start();
for (int i = 0; i < queries; i++)
{
User user = userSet.Where(x => x.UserName == "gstrader").First();
}
entityStopWatch.Stop();
Console.WriteLine("Entity - {0} Queries took {1}", queries, entityStopWatch.ElapsedMilliseconds);
结果:
SP-10000查询占用了2278
实体 -10000查询采取16277