ObjectActivator: Faster object instantiation using lambda expression compilation.
This commit is contained in:
@@ -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))
|
||||
|
||||
36
VAR.Focus.Web/Code/ObjectActivator.cs
Normal file
36
VAR.Focus.Web/Code/ObjectActivator.cs
Normal 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user