EF实例化Context
之前了解到EF实例化一个Entity时占用较长时间,刚刚测试了一下,使用代码如下:
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Reset();
sw.Start();
testEntities entity = new testEntities();
List<User> uselist = entity.User.Where(p => p.UserPwd == "111").ToList();
entity.Dispose();
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds.ToString() + " ms" + " count:" + uselist.Count.ToString());
sw.Reset();
sw.Start();
testEntities entity2 = new testEntities();
List<User> uselist2 = entity2.User.Where(p => p.UserPwd == "111").ToList();
entity2.Dispose();
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds.ToString() + " ms" + " count:" + uselist2.Count.ToString());
Console.Read();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Reset();
sw.Start();
testEntities entity = new testEntities();
List<User> uselist = entity.User.Where(p => p.UserPwd == "111").ToList();
entity.Dispose();
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds.ToString() + " ms" + " count:" + uselist.Count.ToString());
sw.Reset();
sw.Start();
testEntities entity2 = new testEntities();
List<User> uselist2 = entity2.User.Where(p => p.UserPwd == "111").ToList();
entity2.Dispose();
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds.ToString() + " ms" + " count:" + uselist2.Count.ToString());
Console.Read();
}
}
}
执行结果 :
388MS
11MS
可见EF只是第一次打开时候慢,之后就很快了
同样用web项目测试了一下,在一个页面实例一个Entity,然后跳到另外一个页面再实例化一次Entity,结果更上面Console程序一样,第一次费时,第二次很快,其实EF是基于Ado.net 那么它新建连接也是从连接池中获取,所以第二次就快很多了。