如何使用反射创建高性能.NET类? [英] How create High Performance .NET classes using reflection?

查看:127
本文介绍了如何使用反射创建高性能.NET类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,大家都知道Reflecttion是很多的时间比newing一个类的实例,更少的高性能,而且在许多情况下,这是蛮好根据不同的应用需求。

Ok, so we all know Reflecttion is many time less performant than "newing" a class instance, and in many cases this is just fine depending on the application requirements.

问:我们怎样才能创建一个使用后期绑定(反射)策略高性能的.NET类

QUESTION: How can we create high performance .NET classes using a late binding (Reflection) strategy.

我有一个现有的要求,即要求使用反射(的CreateInstance)来创建类的实例,但性能是至关重要的。在我的情况,我为我们的应用程序每一个接收到的SMS消息创建实例。在生产过程中这很容易被每天超过一百万。

I have an existing requirement that demands class instances be created using reflection (CreateInstance), but performance is critical. In my situation I am creating instances for every incoming SMS Message in our application. During production this could easily be over a million per day.

我想听到和分享如何创建.NET类的一些想法,而不用直接引用在code类,例如使用反射。我也在想,如果有一种方法以某种方式缓存类工厂,可以提高创世纪的时间

I would like to hear and share some ideas on how to create .NET classes without directly referencing the classes in code, for example using Reflection. I was also thinking if there is a way to somehow cache a class Factory that can improve the "Creation" time

推荐答案

100万天也不是很多;我只是用 Activator.CreateInstance (快速测试使用 Activator.CreatInstance(类型)显示我的弱旅笔记本电脑可以从创建1M对象键入在约2秒)。

1 million a day is not a lot; I'd just use Activator.CreateInstance (a quick test using Activator.CreatInstance(Type) shows that on my lowly laptop it can create 1M objects from aType in ~2s).

在快速创建对象的思考:

Thoughts on creating objects quickly:

  • 使用泛型和:新的()约束(零努力)
  • 使用 DynamicMethod的,写的IL(不硬)
  • use generics and the : new() constraint (zero effort)
  • use DynamicMethod and write the IL (not hard)

办法的实施(而不需要:新的()约束外),如下所示: ObjectFactory.cs

An implementation of the new approach (without needing the : new() constraint externally) is shown here: ObjectFactory.cs.

对于IL例如,看到的短小精悍点网 il.Emit(欧普codes.Newobj,...)

For an IL example, see dapper-dot-net and il.Emit(OpCodes.Newobj, ...)

这篇关于如何使用反射创建高性能.NET类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆