var people = new People()
{
Id = 11,
Name = "Richard",
Age = 31
};
int count = 1_000_000;
var common = HiPerfTimer.Execute(() =>
{
for (int i = 0; i < count; i++)
{
var item = new PeopleCopy()
{
Id = people.Id,
Name = people.Name,
Age = people.Age,
};
}
});
Console.WriteLine(string.Format("common={0} ms", common));
var serialize = HiPerfTimer.Execute(() =>
{
PeopleCopy item = new PeopleCopy();
for (int i = 0; i < count; i++)
{
var rslt = JsonConvert.SerializeObject(people);
item = JsonConvert.DeserializeObject<PeopleCopy>(rslt);
}
});
Console.WriteLine(string.Format("serialize={0} ms", serialize));
var generic = HiPerfTimer.Execute(() =>
{
PeopleCopy item = new PeopleCopy();
for (int i = 0; i < count; i++)
{
item = ExpressionTreeHelper<PeopleCopy>.EntityMap(people);
}
});
Console.WriteLine(string.Format("generic={0} ms", generic));
var copy = HiPerfTimer.Execute(() =>
{
PeopleCopy item = new PeopleCopy();
for (int i = 0; i < count; i++)
{
var aa = people.DeepCopy();
}
});
Console.WriteLine(string.Format("DeepCopy={0} ms", copy));
public class ExpressionTreeHelper<T>
{
public static T EntityMap<TSrc>(TSrc src)
{
return ExpressionGenericMapper<TSrc, T>.EntityMap(src);
}
}
internal class ExpressionGenericMapper<TSrc, TDst>
{
private static readonly Func<TSrc, TDst> _func = null;
static ExpressionGenericMapper()
{
var parameterExpression = Expression.Parameter(typeof(TSrc), "e");
var list = new List<MemberBinding>();
foreach (var item in typeof(TDst).GetProperties())
{
var property = Expression.Property(parameterExpression, typeof(TSrc).GetProperty(item.Name));
var binding = Expression.Bind(item, property);
list.Add(binding);
}
foreach (var item in typeof(TDst).GetFields())
{
var property = Expression.Field(parameterExpression, typeof(TSrc).GetField(item.Name));
var binding = Expression.Bind(item, property);
list.Add(binding);
}
var miExpression = Expression.MemberInit(Expression.New(typeof(TDst)), list.ToArray());
var lambda = Expression.Lambda<Func<TSrc, TDst>>(miExpression, new[]
{
parameterExpression
});
_func = lambda.Compile();
}
public static TDst EntityMap(TSrc obj)
{
return _func(obj);
}
}
标签:PeopleCopy,people,ExpressionTreeHelper,item,var,new,拷贝,Expression,树泛
From: https://www.cnblogs.com/wesson2019-blog/p/18560057