ObjectActivator: Faster object instantiation using lambda expression compilation.

This commit is contained in:
2016-12-06 02:30:14 +01:00
parent 2aa6ec858b
commit 141d1e8640
3 changed files with 37 additions and 1 deletions

View File

@@ -73,7 +73,7 @@ namespace VAR.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,35 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace VAR.Json
{
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();
}
}
}

View File

@@ -36,6 +36,7 @@
<ItemGroup>
<Compile Include="JsonParser.cs" />
<Compile Include="JsonWriter.cs" />
<Compile Include="ObjectActivator.cs" />
<Compile Include="ParserContext.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>