ObjectActivator: Faster object instantiation using lambda expression compilation.

This commit is contained in:
2016-12-06 02:32:27 +01:00
parent 4127b44bc4
commit 3498ada6ff
4 changed files with 40 additions and 3 deletions

View File

@@ -70,7 +70,7 @@ namespace VAR.Focus.Web.Code.JSON
private object ConvertToType(Dictionary<string, object> obj, Type type)
{
PropertyInfo[] typeProperties = Type_GetProperties(type);
object newObj = Activator.CreateInstance(type);
object newObj = ObjectActivator.CreateInstance(type);
foreach (PropertyInfo prop in typeProperties)
{
if (obj.ContainsKey(prop.Name))

View File

@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace VAR.Focus.Web.Code
{
public class ObjectActivator
{
private static Dictionary<Type, Func<object>> _creators = new Dictionary<Type, Func<object>>();
public static Func<object> GetLambdaNew(Type type)
{
if (_creators.ContainsKey(type))
{
return _creators[type];
}
lock (_creators)
{
NewExpression newExp = Expression.New(type);
LambdaExpression lambda = Expression.Lambda(typeof(Func<object>), newExp);
Func<object> compiledLambdaNew = (Func<object>)lambda.Compile();
_creators.Add(type, compiledLambdaNew);
}
return _creators[type];
}
public static object CreateInstance(Type type)
{
Func<object> creator = GetLambdaNew(type);
return creator();
}
}
}