性能分析 ADO.NET 和实体框架 [英] Performance analyze ADO.NET and Entity Framework

查看:21
本文介绍了性能分析 ADO.NET 和实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪一个提供更好的性能?ADO.NET 或实体框架.

Which one gives better performance? ADO.NET or Entity Framework.

这是我要分析的两种方法.

These are the two method I want to analyze.

ADO.NET 测试方法

public void ADOTest()
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    using (SqlConnection con = new SqlConnection(connection))
    {
        string Query = "select * from Product ";
        SqlDataAdapter da = new SqlDataAdapter(Query, con);
        DataSet ds = new DataSet();
        con.Open();
        da.Fill(ds);
        DataView dv = ds.Tables[0].DefaultView;
    }
    stopwatch.Stop();
    Console.WriteLine("ADO.NET Time Elapsed={0}", stopwatch.Elapsed);
}

实体框架测试方法

public void EFTest()
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    var list = _OnlineStoreEntities.Products.ToList();
    stopwatch.Stop();
    Console.WriteLine("Entity Framework Elapsed={0}", stopwatch.Elapsed);
}

第一次执行的结果

当我运行上述方法超过 100 次时.平均执行时间如图所示:

When I ran this above method in more than 100 times. The average execution time is shown in the image:

无论实体框架花费超过 4 毫秒,ADO.NET 仅花费 2 毫秒.

ADO.NET took only 2 milliseconds whether Entity Framework took more than 4 milliseconds.

导致第二次执行

当我一次又一次地运行这个方法时.ADO.NET 和 EF 之间的平均执行时间并不多:

When I ran this method again and again in single run. The average execution time between ADO.NET and EF is not much more:

问题

  1. 我认为 EF 在第一次执行时性能非常差那我们为什么要使用 EF?
  2. 为什么 EF 第二次执行比第一次执行更快?

推荐答案

  1. EF 首次将元数据加载到内存中,这需要一些时间.它从 edmx 文件或源代码(如果您首先使用代码)构建模型的内存表示.实际上 EF 是在 ADO.NET 之上构建的,所以它不能更快​​.但它使开发速度快得多.并提高代码的可维护性.
  2. 见 1

查看 msdn 文章 性能注意事项(实体框架)

Take a look on msdn article Performance Considerations (Entity Framework)

这篇关于性能分析 ADO.NET 和实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆