File tree Expand file tree Collapse file tree 2 files changed +45
-2
lines changed
src/DotNetToolkit.Repository.InMemory/Internal Expand file tree Collapse file tree 2 files changed +45
-2
lines changed Original file line number Diff line number Diff line change 22{
33 using Extensions . Internal ;
44 using System ;
5+ using System . Collections . Concurrent ;
6+ using System . Collections . Generic ;
57 using System . Linq ;
68 using System . Reflection ;
79 using Utility ;
810
911 internal static class CloneableHelper
1012 {
13+ private readonly static ConcurrentDictionary < Type , IEnumerable < PropertyInfo > > _cache = new ConcurrentDictionary < Type , IEnumerable < PropertyInfo > > ( ) ;
14+
1115 public static object DeepCopy ( object entity )
1216 {
1317 Guard . NotNull ( entity , nameof ( entity ) ) ;
1418
15- var newItem = Activator . CreateInstance ( entity . GetType ( ) ) ;
16- var properties = entity . GetType ( ) . GetRuntimeProperties ( ) . Where ( x => x . IsPrimitive ( ) ) ;
19+ var type = entity . GetType ( ) ;
20+ var newItem = FastActivator . CreateInstance ( type ) ;
21+
22+ if ( ! _cache . TryGetValue ( type , out IEnumerable < PropertyInfo > properties ) )
23+ {
24+ properties = type . GetRuntimeProperties ( ) . Where ( x => x . IsPrimitive ( ) ) ;
25+
26+ _cache [ type ] = properties ;
27+ }
1728
1829 foreach ( var propInfo in properties )
1930 {
Original file line number Diff line number Diff line change 1+ namespace DotNetToolkit . Repository . InMemory . Internal
2+ {
3+ using System ;
4+ using System . Collections . Concurrent ;
5+ using System . Linq . Expressions ;
6+ using System . Reflection ;
7+
8+ internal static class FastActivator
9+ {
10+ private readonly static ConcurrentDictionary < Type , Func < object > > _cache = new ConcurrentDictionary < Type , Func < object > > ( ) ;
11+
12+ public static T CreateInstance < T > ( ) where T : class
13+ {
14+ return ( T ) CreateInstance ( typeof ( T ) ) ;
15+ }
16+
17+ public static object CreateInstance ( Type type )
18+ {
19+ if ( ! type . GetTypeInfo ( ) . IsClass )
20+ return Activator . CreateInstance ( type ) ;
21+
22+ if ( ! _cache . TryGetValue ( type , out Func < object > f ) )
23+ {
24+ f = Expression . Lambda < Func < object > > ( Expression . New ( type ) ) . Compile ( ) ;
25+
26+ _cache [ type ] = f ;
27+ }
28+
29+ return f ( ) ;
30+ }
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments