ObjectActivator: Cache creators on a dictionary.

This commit is contained in:
2019-11-24 04:11:15 +01:00
parent 5bf8b85416
commit 73ab9292e7

View File

@@ -6,7 +6,7 @@ namespace VAR.Json
{ {
public class ObjectActivator public class ObjectActivator
{ {
private static Dictionary<Type, Func<object>> _creators = new Dictionary<Type, Func<object>>(); private static readonly Dictionary<Type, Func<object>> _creators = new Dictionary<Type, Func<object>>();
public static Func<object> GetLambdaNew(Type type) public static Func<object> GetLambdaNew(Type type)
{ {
@@ -17,13 +17,18 @@ namespace VAR.Json
lock (_creators) lock (_creators)
{ {
if (_creators.ContainsKey(type))
{
return _creators[type];
}
NewExpression newExp = Expression.New(type); NewExpression newExp = Expression.New(type);
LambdaExpression lambda = Expression.Lambda(typeof(Func<object>), newExp); LambdaExpression lambda = Expression.Lambda(typeof(Func<object>), newExp);
Func<object> compiledLambdaNew = (Func<object>)lambda.Compile(); Func<object> compiledLambdaNew = (Func<object>)lambda.Compile();
_creators.Add(type, compiledLambdaNew); _creators.Add(type, compiledLambdaNew);
return _creators[type];
} }
return _creators[type];
} }
public static object CreateInstance(Type type) public static object CreateInstance(Type type)