使用实例池 EFCore2.0 为DbContext引入新的注册方式:透明地注册了 DbContext实例池,使用这种方式可以避免始终创建新的实例,EF Core 将重置其状态并将其存储在内部池中;当下次请求新的实例时,将返回该共用实例,而不是设置新的实例
使用示例:
1
services . AddDbContext < HandshakesWebDBContext >( options => options . UseSqlServer ( connectionConfiguration . WebDBConnection ));
替换为:
1
2
builder . Services . AddDbContextPool < HandshakesWebDBContext >( options => options . UseSqlServer ( connectionConfiguration . WebDBConnection ), poolSize : 80 );
//注意设置最大连接数,一旦超过默认配置的连接池最大数量,会回退到按需创建实例的行为
基准测试(官方) 测试代码 :
方法 数量 平均值 错误 标准偏差 Gen 0 Gen 1 Gen 2 已分配 WithoutContextPooling 1 701.6 us 26.62 us 78.48 us 11.7188 - - 50.38 KB WithContextPooling 1 350.1 us 6.80 us 14.64 us 0.9766 - - 4.63 KB
注意事项:虽然在大部分情况下这种做法对性能的提升可能并不是非常明显,但是这是一种好的实践方式,避免资源浪费的同时对性能带来一定的提升。
使用拆分查询 了解什么是 笛尔卡乘积 ?
通俗地来讲指的是从两个集合(Set)中的元素组成新的配对集合 以麦当劳套餐来比喻,门店将汉堡线和饮品线上的每个产品集合组成一个新的套餐会有多少种套餐
在数据库中的表现形式正是联表查(join)操作 两个表在数据量不是很大的情况下查询来讲可能对性能影响模棱两可 但是对于一些因业务需求日益增加列的大宽表以及数据存量过大的表来讲就会产生查询过慢以及数据冗余的问题 尤其适合一对多且子表数据量较大的场景。
看一段Linq代码:
1
2
3
4
5
6
7
8
var data = ctx . As
. Include ( x => x . Bs )
. Include ( x => x . Cs )
. ThenInclude ( x => x . D1s )
. Include ( x => x . Cs )
. ThenIncude ( x => x . C1s )
. ThenInclude ( x => x . D2s )
. ToList ();
监控查看生成的Sql语句:
1
2
3
4
5
6
7
8
9
10
11
12
SELECT [ A ].[ Id ], [ A ].[ Name ],
[ B ].[ Id ], [ B ].[ AId ], [ B ].[ Name ],
[ C ].[ Id ], [ C ].[ AId ], [ C ].[ Name ],
[ D1 ].[ Id ], [ D1 ].[ CId ], [ D1 ].[ Name ],
[ C1 ].[ Id ], [ C1 ].[ CId ], [ C1 ].[ Name ],
[ D2 ].[ Id ], [ D2 ].[ C1Id ], [ D2 ].[ Name ]
FROM [ As ] AS [ A ]
LEFT JOIN [ Bs ] AS [ B ] ON [ A ].[ Id ] = [ B ].[ AId ]
LEFT JOIN [ Cs ] AS [ C ] ON [ A ].[ Id ] = [ C ].[ AId ]
LEFT JOIN [ D1s ] AS [ D1 ] ON [ C ].[ Id ] = [ D1 ].[ CId ]
LEFT JOIN [ C1s ] AS [ C1 ] ON [ C ].[ Id ] = [ C1 ].[ CId ]
LEFT JOIN [ D2s ] AS [ D2 ] ON [ C1 ].[ Id ] = [ D2 ].[ C1Id ]
毫无疑问,这一段糟糕的sql语句,假设每张表的数据量都很大的情况下,这对查询无疑是一种很大的负担,如果条件再复杂一点,对整个语句的分析也是很糟糕的。关于阿里开发规范中定义超过3张表的join查询是被禁止的 (未查证) ,这个可能只是为了开发规范和管理,从技术角度出发,其实是没有这样的原则性问题的。
解决方案:使用SplitQuery,从字面意义就可以理解,即将这些join查询拆分成单个查询来执行
示例代码(推荐):
1
2
3
4
5
6
7
8
9
var data = ctx . As
. Include ( x => x . Bs )
. Include ( x => x . Cs )
. ThenInclude ( x => x . D1s )
. Include ( x => x . Cs )
. ThenIncude ( x => x . C1s )
. ThenInclude ( x => x . D2s )
. AsSplitQuery () // 设置为拆分查询
. ToList ();
当然也可以在全局进行配置 (但是一般不推荐这样做,最好根据每个查询的实际情况,使用上面推荐的方式)
1
builder . Services . AddDbContext < CRSGEntityDbContext >( options => options . UseSqlServer ( builder . Configuration [ "ConnectionStrings:FiinGroupDB" ], o => o . UseQuerySplittingBehavior ( QuerySplittingBehavior . SplitQuery )));
生成的sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
SELECT [ a ].[ Id ], [ a ].[ OtherColumns ]
FROM [ As ] AS [ a ]
SELECT [ b ].[ Id ], [ b ].[ AId ], [ b ].[ OtherColumns ]
FROM [ Bs ] AS [ b ]
INNER JOIN [ As ] AS [ a ] ON [ b ].[ AId ] = [ a ].[ Id ]
SELECT [ c ].[ Id ], [ c ].[ AId ], [ c ].[ OtherColumns ]
FROM [ Cs ] AS [ c ]
INNER JOIN [ As ] AS [ a ] ON [ c ].[ AId ] = [ a ].[ Id ]
SELECT [ d1 ].[ Id ], [ d1 ].[ CId ], [ d1 ].[ OtherColumns ]
FROM [ D1s ] AS [ d1 ]
INNER JOIN [ Cs ] AS [ c ] ON [ d1 ].[ CId ] = [ c ].[ Id ]
WHERE [ c ].[ AId ] IN ( SELECT [ a ].[ Id ] FROM [ As ] AS [ a ])
SELECT [ c1 ].[ Id ], [ c1 ].[ CId ], [ c1 ].[ OtherColumns ]
FROM [ C1s ] AS [ c1 ]
INNER JOIN [ Cs ] AS [ c ] ON [ c1 ].[ CId ] = [ c ].[ Id ]
WHERE [ c ].[ AId ] IN ( SELECT [ a ].[ Id ] FROM [ As ] AS [ a ])
SELECT [ d2 ].[ Id ], [ d2 ].[ C1Id ], [ d2 ].[ OtherColumns ]
FROM [ D2s ] AS [ d2 ]
INNER JOIN [ C1s ] AS [ c1 ] ON [ d2 ].[ C1Id ] = [ c1 ].[ Id ]
WHERE [ c1 ].[ CId ] IN ( SELECT [ c ].[ Id ] FROM [ Cs ] AS [ c ] WHERE [ c ].[ AId ] IN ( SELECT [ a ].[ Id ] FROM [ As ] AS [ a ]))
可以看到查询被拆分成了独立的语句,逻辑更加清晰,对于数据库来说执行效率也会更好。
注意事项:虽然拆分查询可以通过避免笛尔卡爆炸带来的性能问题,但是也需要根据实际的查询场景来决定是否使用,例如,需要对数据进行排序,分页,分组等操作的时候,为了保证查询结果的正确性,就需要考虑是否要使用拆分查询
关联话题:关于懒加载,其实懒加载的问题原因就等同于在循环中执行sql语句,示例代码:
1
2
3
4
5
6
7
8
//在没有显示加载的情况下,直接循环查询子对象
foreach ( var blog in context . Blogs . ToList ())
{
foreach ( var post in blog . Posts )
{
Console . WriteLine ( $"Blog {blog.Url}, Post: {post.Title}" );
}
}
观察sql日志:
i i i i n n n n f f f f o o o o : : : : a n M E S F M E S F W M E S F W M E S F W d i x E R i x E R H i x E R H i x E R H c e L O c e L O E c e L O E c e L O E s r c E M r c E M R r c E M R r c E M R o o u C o u C E o u C E o u C E s t T [ s t T [ s t T [ s t T [ o o e B o e P [ o e P [ o e P [ n f d [ l f d [ o p f d [ o p f d [ o p t b o t p s ] t p s ] t p s ] . D ] g . D ] t . . D ] t . . D ] t . E b . s E b . ] [ E b . ] [ E b . ] [ n C [ ] n C [ B n C [ B n C [ B t o B t o P A l t o P A l t o P A l i m l A i m o S o i m o S o i m o S o t m o S t m s g t m s g t m s g y a g y a t [ I y a t [ I y a t [ I F n I [ F n I p d F n I p d F n I p d r d d b r d d ] ] r d d ] ] r d d ] ] a ] ] a ] a ] a ] m ( , m ( , = m ( , = m ( , = e 1 e 5 e 1 e 1 w m [ w m [ @ w m [ @ w m [ @ o s b o s p _ o s p _ o s p _ r ) ] r ) ] _ r ) ] _ r ) ] _ k . k . p k . p k . p C [ [ C [ [ _ C [ [ _ C [ [ _ o P R o P B 0 o P B 0 o P B 0 r a a r a l r a l r a l e r t e r o e r o e r o . a i . a g . a g . a g D m n D m I D m I D m I a e g a e d a e d a e d t t ] t t ] t t ] t t ] a e , a e , a e , a e , b r b r b r b r a s [ a s [ a s [ a s [ s = b s = p s = p s = p e [ ] e [ ] e [ ] e [ ] . ] . . @ . . @ . . @ . C , [ C _ [ C _ [ C _ [ o U o _ C o _ C o _ C m C r m p o m p o m p o m o l m _ n m _ n m _ n a m ] a 0 t a 0 t a 0 t n m n = e n = e n = e d a d ' n d ' n d ' n [ n [ 1 t [ 2 t [ 3 t 2 d 2 ' ] 2 ' ] 2 ' ] 0 T 0 ] , 0 ] , 0 ] , 1 y 1 , 1 , 1 , 0 p 0 [ 0 [ 0 [ 1 e 1 C p 1 C p 1 C p ] = ] o ] ] o ] ] o ] ' m . m . m . T m [ m [ m [ e a T a T a T x n i n i n i t d t d t d t ' T l T l T l , y e y e y e p ] p ] p ] C e e e o = = = m ' ' ' m T T T a e e e n x x x d t t t T ' ' ' i , , , m e C C C o o o o u m m m t m m m = a a a ' n n n 3 d d d 0 T T T ' i i i ] m m m e e e o o o u u u t t t = = = ' ' ' 3 3 3 0 0 0 ' ' ' ] ] ]
正确的做法即使用Include或者Load显示加载数据。
使用批处理语句 批处理语句是EFCore7 版本中更新的重要功能,解决了以往版本需要借助第三方库来实现数据的批量更新,删除操作,而且在性能上带来了更大的提升
批量删除 之前版本的做法(不借助第三方库)
1
2
3
4
5
foreach ( var blog in context . Blogs . Where ( b => b . Rating < 3 ))
{
context . Blogs . Remove ( blog );
}
context . SaveChanges ();
使用ExecuteDelete,无论是从语法上还是性能上,批处理操作都优于前者。
c o n t e x t . B l o g s . W h e r e ( b = > b . R a t i n g < 3 ) . E x e c u t e D e l e t e ( ) ;
如果是EFCore版本低于7.0,也可以使用直接执行sql语句 ExecuteSqlRaw 的方式来进行操作
c o n t e x t . D a t a b a s e . E x e c u t e S q l R a w ( " D E L E T E F R O M [ B l o g s ] W H E R E [ R a t i n g ] < 3 " ) ;
批量更新 用法与Delete 基本相同
c o n t e . . x W E t h x . e e B r c l e u o ( t g b e s U = p > d a b t . e R ( a s t e i t n t g e r < s 3 = ) > s e t t e r s . S e t P r o p e r t y ( b = > b . I s V i s i b l e , f a l s e ) ) ;
注意事项:目前仅支持关系型数据库,而且需要由于是及时发送上下文请求,所以如果要支持事务,需要使用显示事务来与其他代码组合
使用非跟踪查询 这个比较简单,在你不需要对查询结果进行任何更新操作的场景下,尽量使用非跟踪查询
v a r b . . l A T o s o g N L s o i T s = r t a ( c c ) o k ; n i t n e g x ( t ) . B l o g s
或者
c v o a n r t e b x l t o . g C s h a = n g c e o T n r t a e c x k t e . r B . l Q o u g e s r . y T T o r L a i c s k t i ( n ) g ; B e h a v i o r = Q u e r y T r a c k i n g B e h a v i o r . N o T r a c k i n g ;
测试代码
d d C C / o o o o / 代 执 u u n n C T A 码 行 b b s s o r s 执 5 l l o o n a N 行 次 e e l l s c o 前 e e o k T 已 e e . . l e r 对 l l W W e d a 数 a a r r s c 据 p p i i : t k 库 s s t t i i 进 e e e e m n 行 d d L L e g 预 T T i i ( 热 i i n n t ) 处 m m e e o 理 e e ( ( o t 4 5 $ $ k i " " m = = T A : e r s M M a N 3 t e e c o 1 o a a k T 8 o s s e r . k u u d a 2 r r c 6 : e e t k T T i i m 2 i i m n s 2 m m e g 9 e e ( . ( ( t ) 8 ( ( o 6 ) ) o t k i m = = m s > > : e c c { t o o e o n n l o t t a k e e p x x s : t t e . . d { B B T e l l i l o o m a g g e p s s 4 s . . } e F A d i s m T r N s i s o " m t T ) e O r ; 5 r a } D c e k m f i s a n " u g ) l ( ; t ) ( . x F i = r > s t x O . r I D d e f = a = u l 1 t ) ( , x 5 = ) > ; x . I d = = 1 ) , 5 ) ; 仅投影需要的字段 严格意义上来讲这是一个意识问题,大多数情况下,为了节省代码量,可以直接使用DataSet 定义的对象来直接进行查询,或者使用Include加载关联表数据,但是在遇到大量数据查询或大量的表连接查询的时候,精准的属性投影对性能就会起到很大的影响
示例代码:
v f { } a o r r e d . . a C a W T c o t h o h n a e L s r i o = e s v l ( t a e c x ( r . t ) W x = ; i r . > t i A e t s x m e . L N i i a n n m e e d ( . a $ S t " t a N a . a r B m t s e W ) i : t { h i ( t " e x m x . x N " a ) m ) e } , I d : { i t e m . I d } " ) ;
上述代码中,我们仅需要查询主表及子表的id和name信息,但是却加载了所有的相关的主表和子表字段,这对性能是一种浪费
解决方案:通过Select投影需要查询的字段
v a r d . . . a W S T t h e o a e l L r e i = e c s ( t t c x ( ( t x ) x = ; . > = A > s x . n I e d w = 1 { ) x . I d , x . N a m e } )
个人习惯性做法
/ a 1 r , 不 q 依 u 赖 e 于 r 数 y 据 库 = 外 键 f j j s 的 r o o e 设 o i i l 置 m n n e c b c d t i i i n n n n e w c c c o o o A n n n { t t t b e e e l x x x o t t t g . . . I B C P d l o o o m s = g m t s e s b n . t o b s n l o o d g n . I c d b o , . m p b m o l e s o n t g t I I I d d d = e e q q d u u . a a p l l o s s s t c c I . . d b c , l o p o m o g m s I e t d n V t a I l d u e = d . p o s t V a l u e } 这种做法对多表联查和大数据量的查询很有用 ,但需要注意的是这种做法并不适合需要更新数据的场景,因为 EF 的更改跟踪仅适用于实体实例。
尽量使用异步方法 EFCore 基本上对所有同步操作方法都提供了对应的异步方法,尽量使用他们避免阻塞,减少对线程的需要和必须发生的线程上下文切换的次数,从而提升性能。
i a / a / a t / w / a T r F r e S a A r o i m a i s L d r i . v t A g . . . . . i a s t p e s r A W A G T s t t e o C c y o s h s r o t a O m i h o n u Q e A o L A r n a n c p u r s u i s = D = t n t E e e e y p s y e = g e n d r ( n B t n a f a 2 e x u H y b c y A c w a w ; s t m i a E ( s a u a A . e g b = n b y i l i s S r h l > u n t t t y a a l e m = c A n v b y ( b e > ( c s c c e l R ) . r ) o y o C e a R a b ; n n n h t a b . t c t a e t l R e e n d i e a x x g B n ( t t t e l g ) i . . s o n b b A g > g l l s s ) o o y 3 g g n = ) s s c . . ( a T F ) w c o i ; a l L r i s i i s t e e s t r n t O c v t A r o e - s D n r e y e t - v n f e e a c a x v l ( u t a u ) l . l a ; t B u t A l a e s o t d y g e n s d c ( i t = > i t . I d = = 1 ) ; 异步编程在efcore中在大多数情况被推荐使用,但是需要注意避免使用异步方法查询文本或二进制数据类型的内容,这样反而会引起性能问题(sqlclient 的问题),issue报告: EF Core - Memory and performance issues with async methods Reading large data (binary, text) asynchronously is extremely slow
避免混合使用同步和异步方法,当你的程序请求量较大的时候,很可能导致连接池耗尽,从而引起的性能问题。
使用Find查找单个目标数据 设计为在已知主键时高效查找单个实体。 Find 首先检查实体是否已被跟踪,如果是,则立即返回该实体。 只有当未在本地跟踪实体时,才执行数据库查询,而First/FirstOrDefault会立即查询数据库。
d d C C / o o o o / 代 u u n n C F F 码 b b s s o i i 执 l l o o n n n 行 e e l l s d d 前 e e o ( ( 已 e e . . l ) ) 对 l l W W e 数 a a r r s f s 据 p p i i : i e 库 s s t t r c 进 e e e e s o 行 d d L L t n 预 T T i i d 热 i i n n t 处 m m e e i t 理 e e ( ( m i 4 5 $ $ e m " " e = = F F t i i o t M M n n o o e e d d k o a a ( ( k s s ) ) : u u : r r f s 2 e e i e 6 0 T T r c 8 . i i s o . 1 m m t n 4 6 e e d 1 ( ( t m ( ( i t m s ) ) m i s e m = = e > > t o t c c o o o o k o n n k t t : e e : x x { t t e { . . l e b b a l l l p a o o s p g g e s s s d e . . T d F F i T i i m i n n e m d d 4 e ( ( } 5 1 1 } ) ) m ; ; s m " s ) " ; ) ; 注意,只能通过键查询的时候可以用。
使用Any判断数据内容 在检查某些数据是否存在的时候,优先使用Any,这样在匹配到第一条数据后,查询就会停止,First因为需要返回数据,增加了数据传输和对象实例化的开销,Count则需要扫描表
d d d C C C o o o o o o / u u u n n n C A C F b b b s s s o n o i l l l o o o n y u r e e e l l l s ( n s e e e o ) t t e e e . . . l ( O l l l W W W e t ) r a a a r r r s i D p p p i i i : m t e s s s t t t e i f e e e e e e m a d d d L L L t e u T T T i i i o l i i i n n n o t t m m m e e e k o ( e e e ( ( ( : o ) 1 2 3 $ $ $ k " " " 2 : t = = = A C F 3 i n o i 7 2 m M M M y u r . 3 e e e e ( n s 4 9 a a a ) t t 2 . t s s s ( O 6 o u u u t ) r m 9 o r r r i D s k e e e m t e m : T T T e i f s i i i m a 2 m m m t e u 5 e e e o l 8 ( ( ( o t t . ( ( ( k o ( 2 ) ) ) : o ) 8 k = = = { : t m > > > e i s l { m c c c a e e o o o p l n n n s a t t t t e p o e e e d s o x x x T e k t t t i d : . . . m T B B B e i { l l l 1 m e o o o } e l g g g 2 a s s s m } p . . . s s A C F " m e n o i ) s d y u r ; " T ( n s ) i i t t ; m t ( O e i r 3 = t D } > e = f m i > a s t u " . i l ) I t t ; d . ( I i = d t = = = 1 = > ) ) 1 i ; ) t , . I 1 d ) ; = = 1 ) , 1 ) ; 使用流式处理 首先了解什么是缓冲和流式处理
缓冲:将需要的数据全部加载到内存中,用于后续的业务逻辑处理 流式处理:按需获取需要的数据并应用到后续的逻辑处理中 形象的理解,缓冲用水桶把水挑起来,然后倒进缸里,流式处理就是用一根水管把水抽到缸里
原则上,流式处理查询的内存要求是固定的:无论查询返回 1 行还是 1000 行,内存要求都相同。另一方面,返回的行数越多,缓冲查询需要的内存越多。 对于产生大型结果集的查询,这可能是一个重要的性能因素。 反之,如果你的查询结果量很小,那么使用缓冲的效果可能返回会更好。
v f { } / a a / o a 一 r r 使 r r 次 用 e 也 性 b b 流 a S 可 d . . . 将 l l 式 c / o 以 o W A W 数 o o 处 h d m 使 u h s h 据 g g 理 o e 用 b e E e 加 s s , D A l r n r 载 L A 每 v s o s e e u e 出 i r 次 a o t E F ( m ( 来 s r 处 r m N n i p e p t a 理 e e u l r y 一 b t m t = a = = 行 l t M e e > b > = o h e r r l c g i t a e p e S o c n h b d . ( o n o i g o l B T ) m t n n s d e l i e e t . ( 实 o t D x e c . b 现 g l o t x o . l s e t . t n o . N P . t g = S e o P e ) t t s o x c a M t s t o r e s t . n t t . s P t s h W . o e W o h W s x i d e h t t t ( r e s . h p e r . P ( ) ( e W o " ) p ( h s A ; p e t " = r s ) > = e ) / > ( 执 p p 行 . p 客 T . = 户 i T > 执 端 t i 行 操 l t p 数 作 e l . 据 . e T 库 S . i 查 t S t 询 a t l r a e t r . s t S W s t i W a t i r h t t ( h s " ( W A " i " A t ) " h ) ) ( . ) " T . A o T " L o ) i A ) s r ) t r ( a ) y ; ( ) ; 流式处理适合处理大量数据需要进行某些业务逻辑的加工或执行,但是数据库又无法支持响应的方法或函数,这个时候可以适用流式处理来进行操作。
使用SQL查询 在某些特殊的情况下,例如一些复杂的sql查询,无法直接使用linq语法来实现的,EFCore也支持直接使用SQL语句进行查询或数据更新操作
基本查询(实体) 场景:最终返回的结果与Dataset中定义的实体一致
/ / a / a 使 执 r 执 r 用 行 行 F 表 b . . 存 b . . r 查 l F T 储 l F T o 询 o r o 过 o r o m g o L 程 g o L S s m i 查 s m i q S s 询 S s l = q t 返 = q t l ( 回 l ( c ( ) 实 c ( ) o $ ; 体 o $ ; n " n " t S t E e E e X x L x E t E t C . C . U B T B T l l E o o g g d s F s b R o O . M G e d t b M o o . s B t l P o o g p s u " l ) a r B l o g s " ) 标量查询(非实体) 场景:最终返回的结果为自定义结构,而非数据库实体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//使用SqlQuery
//执行查询,返回单个字段
var ids = context . Database
. SqlQuery < int >( $"SELECT [BlogId] FROM [Blogs]" )
. ToList ();
//执行查询,返回自定义数据结构
var comments = context . Database
. SqlQuery < int >( $"SELECT b.[BlogId],c.[CommnetContent] FROM [Blogs] b JOIN [Comments] c on b.BlogId = c.BlogId" )
. ToList ();
public class CustomBlog {
public int BlogId
public string CommnetContent
}
执行非查询SQL 场景:提交更新,删除等操作,不关注返回结果
c c / / / o 使 执 n 执 n 用 行 t 行 t E 更 e 删 e x 新 x 除 x e t t c . . u D D t a a e t t S a a q b b l a a s s e e . . E E x x e e c c u u t t e e S S q q l l ( ( $ $ " " U D P E D L A E T T E E [ F B R l O o M g s [ ] B l S o E g T s ] [ U W r H l E ] R E = I N d U L = L 1 " W ) H ; E R E I d = 1 " ) ; SQL参数 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//使用FromSql
//此代码无效,因为数据库不允许将列名(或架构的任何其他部分)参数化
var propertyName = "User" ;
var propertyValue = "johndoe" ;
var blogs = context . Blogs
. FromSql ( $"SELECT * FROM [Blogs] WHERE {propertyName} = {propertyValue}" )
. ToList ();
//正确姿势:使用 FromSqlRaw
var columnName = "Url" ;
var columnValue = new SqlParameter ( "columnValue" , "http://SomeURL" );
var blogs = context . Blogs
. FromSqlRaw ( $"SELECT * FROM [Blogs] WHERE {columnName} = @columnValue" , columnValue )
. ToList ();
其他关联性优化 除了针对EFCore本身的一些优化技巧之外,还有一些技巧可以帮助我们提升数据查询的效率,我们可以利用vs的调试工具帮助我们监听内存使用,CPU占用率等指标,查找瓶颈,总结主要从以下几个方面进行优化
尽量避免循环内查询,分析实际的业务逻辑,尽可能的一次性从数据库加载所有需要的数据,再进行循环处理 分片处理条件数据,例如使用Chunk,使用流式处理大批量的数据集的运算 使用合理的数据结构,例如在不关注数据顺序的场景下使用Dictionary或HashSet代替List等 使用缓存减少热点数据的访问(按需设计) 使用数据表索引及物化视图(数据库) 采用分库分表,读写分离,使用ES进行检索(架构级优化) 利用多线程并发提升效率(不到万不得已,慎用) 总结 EFCore的优化主要是从几个方面来进行: 1.减少数据库的交互,通过连接复用,上下文缓存等 2.减少内存的使用,例如使用流式处理,分页查询等 3.降低查询复杂度,尽量在程序中处理复杂的逻辑
保持良好的编码习惯,使用正确的数据结构和处理逻辑,优化应该是渐进式的,先正确的满足需求,在遇到性能问题的时候借助代码或工具去分析瓶颈,再去进行针对性的优化,不要为了优化而牺牲需求和浪费工作量。
最后留给大家一段问题代码示例,感兴趣的童鞋可以尝试利用上述手段优化这段代码,看看效率提升有多少:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var configuration = new ConfigurationBuilder ()
. SetBasePath ( AppDomain . CurrentDomain . BaseDirectory )
. AddUserSecrets < Program >()
. AddJsonFile ( "appsettings.json" , optional : true , reloadOnChange : true )
. Build ();
var serviceProvider = new ServiceCollection ()
. AddDbContext < YouContext >( options =>
options . UseSqlServer ( configuration [ "ConnectionStrings:YourContext" ])
. EnableSensitiveDataLogging ()
. UseLoggerFactory ( LoggerFactory . Create ( builder =>
{
builder . AddConsole (). AddFilter (( category , level ) => category == DbLoggerCategory . Database . Command . Name && level == LogLevel . Information );
})))
. BuildServiceProvider ();
using ( var scope = serviceProvider . CreateScope ())
{
var context = scope . ServiceProvider . GetRequiredService < YourContext >();
context . Database . SetCommandTimeout ( 999 );
var data = context . RELATIONSHIP . Where ( x => x . workflow_state == 3 ). OrderBy ( it => it . relationship_guid ). Take ( 100000 ). ToList ();
var tempData = data . Select ( it => new Temp { aId = it . entity_from_guid , bId = it . entity_to_guid , deg = 0 }). ToList ();
foreach ( var item in tempData )
{
item . deg = GetInterConnectResult ( item . aId , item . bId );
}
int GetInterConnectResult ( Guid aId , Guid bId )
{
HashSet < Bo > boData = new ();
for ( int i = 1 ; i <= 3 ; i ++)
{
if ( boData . Any ( it => it . guid == bId )) break ;
var addIds = boData . Where ( it => it . deg == i - 1 ). Select ( it => it . guid ). Distinct (). ToList ();
var addRelationships = context . Table1 . Where ( it => addIds . Contains ( it . aid ) || addIds . Contains ( it . bid ));
var addDegEntities = addRelationships . Select ( it => new
{
efguid = it . aid ,
etguid = it . bid
}). Union ( addRelationships . Select ( it => new
{
efguid = it . bid ,
etguid = it . aid
}))
. Select ( it => new Bo { guid = it . etguid , deg = i })
. ToHashSet () ?? new ();
boData . UnionWith ( addDegEntities ?? new ());
}
return boData ?. OrderByDescending ( it => it . deg )?. FirstOrDefault ( it => it . guid . Equals ( bId ))?. deg ?? 0 ;
}
}