[转]How to Improve Entity Framework Add Performance?

本文转自:http://entityframework.net/improve-ef-add-performance

When you overuse the Add() method for multiple entities, your application suffers from performance issues.

1

using (var ctx = new CustomerContext())

2

{

3

    foreach(var line in lines)

4

    {

5

        var customer = new Customer();

6

        // ...code...

7

        ctx.Customers.Add(customer);

8

    }

9


10

    ctx.SaveChanges();

11

}

StackOverflow Related Questions

Answer

Is Entity Framework Add Really Slow?

In fact, the Add method is not slow at all. Adding an entity to a list cannot be that slow. It‘s the DetectChanges method invoked inside the Add method which is insanely slow!

Using the Add method in a loop is usually a poor practice which impacts your application performance severely when poorly used.

  • USE AddRange over Add (Recommended)
  • SET AutoDetectChanges to false
  • SPLIT SaveChanges in multiple batches

Use AddRange over Add (Recommended)

When adding multiple entities, you should always use Entity Framework AddRange once with a list instead of calling multiple time the Add method.

Why?

  • The Add method DetectChanges after every records added.
  • The AddRange method DetectChanges after all records are added.

Performance Comparisons

Operations 100 Entities 1,000 Entities 10,000 Entities
Add 15 ms 1,050 ms 105,000 ms
AddRange 1 ms 10 ms 120 ms

Note:

  • *: SaveChanges time not included
  • **: Entity with two relations

How?

  1. CREATE a list
  2. ADD entity to the list
  3. USE AddRange with the list
  4. SaveChanges
  5. Done!

1

using (var context = new EntityContext())

2

{

3

    // 1. CREATE a list

4

    List<Customer>  list = new List<Customer>();

5


6

    for(int i = 0; i < 2000; i++)

7

    {

8

        var customer = new Customer();

9

        // ...code...

10


11

        // 2. ADD entity to the list

12

        list.Add(customer);

13

    }

14


15

    // 3. USE AddRange with the list

16

    context.Customers.AddRange(list);

17


18

    // 4. SaveChanges

19

    ctx.SaveChanges();

20


21

    // 5. Done!

22

}

Try it online

SET AutoDetectChanges to false

When adding multiple entities, if you cannot use AddRange, set Entity Framework AutoDetectChanges to false

Why?

  • The Add method DetectChanges after every records added.

By disabling AutoDetectChanges, the DetectChanges method will only be invoked when you do it.

Performance Comparisons

Operations 100 Entities 1,000 Entities 10,000 Entities
True (Default) 15 ms 1,050 ms 105,000 ms
False 1 ms 14 ms 180 ms

Note:

  • *: SaveChanges time not included
  • **: Entity with two relations

How?

  1. SET AutoDetectChangesEnabled = false
  2. CALL DetectChanges before SaveChanges
  3. SaveChanges
  4. Done!

1

using (var context = new EntityContext())

2

{

3

    // 1. SET AutoDetectChangesEnabled = false

4

    context.Configuration.AutoDetectChangesEnabled = false;

5


6

    List<Customer>  list = new List<Customer>();

7

?

8

    for(int i = 0; i < 2000; i++)

9

    {

10

        var customer = new Customer();

11

        // ...code...

12


13

        list.Add(customer);

14

    }

15


16

    context.Customers.AddRange(list);

17


18

    // 2. CALL DetectChanges before SaveChanges

19

    context.ChangeTracker.DetectChanges();

20


21

    // 3. SaveChanges

22

    context.SaveChanges();

23


24

    // 4. Done!

25

}

Try it online

SPLIT SaveChanges into multiple batches

This solution is not recommended. When adding multiple entities, split entities with a batch size in multiple different contexts.

Why?

More tracking entities your context contains, slower the DetectChanges method is! So by reducing the number of entities by context, you improve the performance.

Performance Comparisons

Operations 100 Entities 1,000 Entities 10,000 Entities
Unlimited 15 ms 1,050 ms 105,000 ms
10 3 ms 40 ms 350 ms
100 15 ms 125 ms 1,200 ms
1,000 15 ms 1,050 ms 10,200 ms

Note:

  • *: SaveChanges time not included
  • **: Entity with two relations

How

  1. CREATE a batchSize variable
  2. CALL SaveChanges before creating a new batch
  3. CALL SaveChanges
  4. Done!

1

// 1. CREATE a batchSize variable

2

int batchSize = 400;

3


4

var context = new EntityContext();

5

?

6

for(int i = 0; i <= 2000; i++)

7

{

8

    // 2. CALL SaveChanges before creating a new batch

9

    if (i != 0 && i%batchSize == 0)

10

    {

11

        context.SaveChanges();

12

        context = new EntityContext();

13

    }

14


15

    var customer = new Customer();

16

    // ...code...

17


18

    context.Customers.Add(customer);

19

}

20

?

21

// 3. CALL SaveChanges

22

context.SaveChanges();

23

?

24

// 4. Done!

Try it online

原文地址:https://www.cnblogs.com/freeliver54/p/9507049.html

时间: 2024-10-12 07:39:29

[转]How to Improve Entity Framework Add Performance?的相关文章

Entity Framework学习(一) - Entity Framework Add and Attach and Entity States

Entity Framework Add and Attach and Entity States Entity Framewokr 新增.附加.实体状态 This topic will cover how to add and attach entities to a context and how Entity Framework processes these during SaveChanges. Entity Framework takes care of tracking the s

Entity Framework 6 预热、启动优化

虽然文章题目是针对EF的,但涉及的内容不仅仅是EF. 场景介绍 目前在做的一个项目,行业门户,项目部分站点按域名划分如下: user.xxx.com:用户登陆注册 owner.xxx.com:个人用户后台 company.xxx.com:企业后台 manage.xxx.com:网站管理 其中user.xxx.com为个人用户及企业用户登陆入口,manage.xxx.com/login为网站管理后台登陆入口. 四个项目都是mvc4+ef6+autofac+automapper. 补充信息: .ne

[XAF] How to improve the application&#39;s performance

https://www.devexpress.com/Support/Center/Question/Details/T148978 The best way to determine the precise cause of a performance problem is to profile your application using a specialized performance profiler tool, e.g., AQTime, ANTS Performance Profi

Why you should use async tasks in .NET 4.5 and Entity Framework 6

Improve response times and handle more users with parallel processing Building a web application using non blocking calls to the data layer is a great way to increase the scalability of your system. Performing a task asynchronously frees up the worke

Entity Framework学习(二) - Entity Framework Automatic Detect Changes

When using most POCO entities the determination of how an entity has changed (and therefore which updates need to be sent to the database) is handled by the Detect Changes algorithm. Detect Changes works by detecting the differences between the curre

Entity Framework 继承

1. Table per Hierarchy 基类和继承类存储在同一张数据表中,通过一个专门的字段(Identifier Column)进行区分. protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Employee>() .Map<FullTimeEmployee>(m =>

Professional C# 6 and .NET Core 1.0 - 38 Entity Framework Core

本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 38 Entity Framework Core ----------------------------------------------------------------------- What's In This Chapter? Introducing Entity Framework Core 1.0 Using Depe

Entity Framework Code-First(23):Entity Framework Power Tools

Entity Framework Power Tools: Entity Framework Power Tools (currently in beta 3) has been released. EF Power Tools is useful mainly in reverse engineering and generating read-only entity data model for code-first. Download and install Power Tools fro

[转]Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10)

本文转自:http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application Creating an Entity Framework Data Model for an ASP.NET MVC Application (1 of 10) By