本文转自: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

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

  1. [2014-09-18]Entity Framework 6 预热、启动优化

    好久没写博客了,终于憋出了一个大招,现在总结下. 虽然文章题目是针对EF的,但涉及的内容不仅仅是EF. 场景介绍 目前在做的一个项目,行业门户,项目部分站点按域名划分如下: user.xxx.com: ...

  2. Access MongoDB Data with Entity Framework 6

    This article shows how to access MongoDB data using an Entity Framework code-first approach. Entity ...

  3. Entity Framework 6 预热、启动优化

    虽然文章题目是针对EF的,但涉及的内容不仅仅是EF. 场景介绍 目前在做的一个项目,行业门户,项目部分站点按域名划分如下: user.xxx.com:用户登陆注册 owner.xxx.com:个人用户 ...

  4. Performance Considerations for Entity Framework 4, 5, and 6

    Performance Considerations for Entity Framework 4, 5, and 6 https://msdn.microsoft.com/en-sg/data/hh ...

  5. [XAF] How to improve the application's performance

    [自己的解决方案]数据量大时,可显著提升用户使用体验! 1.Root ListView 参考官方的E1554 点击导航菜单后首先跳出查询条件设置窗体进行设置 可设置查询方案或查询方案的查询条件,排序字 ...

  6. 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 usi ...

  7. Entity Framework与ADO.NET批量插入数据性能测试

    Entity Framework是.NET平台下的一种简单易用的ORM框架,它既便于Domain Model和持久层的OO设计,也提高了代码的可维护性.但在使用中发现,有几类业务场景是EF不太擅长的, ...

  8. Code First :使用Entity. Framework编程(8) ----转发 收藏

    第8章 Code First将走向哪里? So far, this book has covered all of the Code First components that reached the ...

  9. Code First :使用Entity. Framework编程(7) ----转发 收藏

    第7章 高级概念 The Code First modeling functionality that you have seen so far should be enough to get you ...

随机推荐

  1. Alpha 冲刺 (9/10)

    队名 火箭少男100 组长博客 林燊大哥 作业博客 Alpha 冲鸭鸭鸭鸭鸭鸭鸭鸭! 成员冲刺阶段情况 林燊(组长) 过去两天完成了哪些任务 协调各成员之间的工作 多次测试软件运行 学习OPENMP ...

  2. java利用反射获取对象前后修改的内容(用于日志记录)

    import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Metho ...

  3. tomcat 配置 使用 HTTPS

    1.生成证书 keytool -genkeypair -alias "tomcat" -keyalg "RSA" -keystore "d:\temp ...

  4. boost-字符文本处理

    1.lexical_cast 一些常见的数值,字符互转函数: 整型int: itoa()._itoa_s atoi()._ttoi 无符号整型unsigned int: _ultoa_s()._ult ...

  5. Authorization Security for Mongodb

    To keep security for the mongodb server, we can create an authorized machanism. db.createUser( { use ...

  6. Http协议和Tomcat服务器

    Http协议和Tomcat服务器 什么是Http协议 HTTP,超文本传输协议(HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议. Http协议的组成 Ht ...

  7. Python之旅Day1 数据类型初识(数字|字符串|列表|数据运算) 编码 表达式(if...else|for|while)

    初识PYTHON Python(英国发音:/ˈpaɪθən/ 美国发音:/ˈpaɪθɑːn/), 是一种面向对象的解释型计算机程序设计语言,由荷兰人Guido van Rossum(吉多·范罗苏姆)于 ...

  8. 【算法python实现】 -- 不同路径II

    原题:https://leetcode-cn.com/problems/unique-paths-ii/ 思路 与上题相同,不过是加了路障.地图上每一格都有两个状态,有路障或无路障,分别以1和0表示其 ...

  9. 仿B站项目——(1)计划,前端工程

    计划 现打算: 计划用webpack打包 + 模板语言 + jquery + jquery ui + bootstrap做一个仿B站的静态网站. 网站兼容手机浏览器端. 部分模块打算仿照SPA用js加 ...

  10. 利用SSH反向隧道,连接内网服务器

    前言 公司有一台文件服务器(内部使用,无外网IP),上面主要安装了SVN服务,用来存储和共享各部门的文档,因为都是内网,直接远程(mstsc)上去就可以方便维护,但最近公司租了新的办公室,部分员工被分 ...