diff --git a/VAR.Json/JsonParser.cs b/VAR.Json/JsonParser.cs index f3bf341..1c30c65 100644 --- a/VAR.Json/JsonParser.cs +++ b/VAR.Json/JsonParser.cs @@ -73,7 +73,7 @@ namespace VAR.Json private object ConvertToType(Dictionary 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)) diff --git a/VAR.Json/ObjectActivator.cs b/VAR.Json/ObjectActivator.cs new file mode 100644 index 0000000..69ed4f5 --- /dev/null +++ b/VAR.Json/ObjectActivator.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace VAR.Json +{ + public class ObjectActivator + { + private static Dictionary> _creators = new Dictionary>(); + + public static Func GetLambdaNew(Type type) + { + if (_creators.ContainsKey(type)) + { + return _creators[type]; + } + + lock (_creators) + { + NewExpression newExp = Expression.New(type); + LambdaExpression lambda = Expression.Lambda(typeof(Func), newExp); + Func compiledLambdaNew = (Func)lambda.Compile(); + + _creators.Add(type, compiledLambdaNew); + } + return _creators[type]; + } + + public static object CreateInstance(Type type) + { + Func creator = GetLambdaNew(type); + return creator(); + } + } +} diff --git a/VAR.Json/VAR.Json.csproj b/VAR.Json/VAR.Json.csproj index 00abf9a..3b196d2 100644 --- a/VAR.Json/VAR.Json.csproj +++ b/VAR.Json/VAR.Json.csproj @@ -36,6 +36,7 @@ +