Skip to content

Commit 031b5e2

Browse files
Merge pull request #518 from johelvisguzman/fast-actvator
Added a fast activator to the in-memory context for increasing performance
2 parents 6bd52bd + af7a987 commit 031b5e2

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/DotNetToolkit.Repository.InMemory/Internal/CloneableHelper.cs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,29 @@
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
{
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
}

0 commit comments

Comments
 (0)