ObjectActivator: Faster object instantiation using lambda expression compilation.
This commit is contained in:
@@ -73,7 +73,7 @@ namespace VAR.Json
|
|||||||
private object ConvertToType(Dictionary<string, object> obj, Type type)
|
private object ConvertToType(Dictionary<string, object> obj, Type type)
|
||||||
{
|
{
|
||||||
PropertyInfo[] typeProperties = Type_GetProperties(type);
|
PropertyInfo[] typeProperties = Type_GetProperties(type);
|
||||||
object newObj = Activator.CreateInstance(type);
|
object newObj = ObjectActivator.CreateInstance(type);
|
||||||
foreach (PropertyInfo prop in typeProperties)
|
foreach (PropertyInfo prop in typeProperties)
|
||||||
{
|
{
|
||||||
if (obj.ContainsKey(prop.Name))
|
if (obj.ContainsKey(prop.Name))
|
||||||
|
|||||||
35
VAR.Json/ObjectActivator.cs
Normal file
35
VAR.Json/ObjectActivator.cs
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,7 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Compile Include="JsonParser.cs" />
|
<Compile Include="JsonParser.cs" />
|
||||||
<Compile Include="JsonWriter.cs" />
|
<Compile Include="JsonWriter.cs" />
|
||||||
|
<Compile Include="ObjectActivator.cs" />
|
||||||
<Compile Include="ParserContext.cs" />
|
<Compile Include="ParserContext.cs" />
|
||||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
Reference in New Issue
Block a user