利用dynamic来提供动态方法的性能

前段时间做了一个worklist的项目,有部分是利用xml配置DICOM的tag,然后根据xml把DICOM的Dataset转为实体类,或者把实体类转为Dataset。

当中主要应用了反射来调用Dataset的put方法, 但是发现性能很慢, 一个解析映射花了几百毫秒。


解决办法:

利用dynamic来替换反射:

dynamic temp = new ExampleClass();
temp.someMethod();




当然, 如果非要用Reflection, 可以进行一些优化:

Avoid using Type.InvokeMember to call late-bound methods Type.InvokeMember is the slowest way to invoke a member via reflection. If your scenario doesn't involve COM interop invocation (something which Type.InvokeMember makes easier), consider other alternatives for setting up calls to members obtained through late-bound methods.

Avoid case-insensitive member lookups When calling both the plural and non-plural GetXX APIs, avoid specifying BindingFlags.IgnoreCase as a binding flag argument as it has a significant invocation and working set costs. Metadata is case sensitive and to perform an "ignore case" operation, reflection needs to obtain the metadata string names for all members of a type and then do a case-insensitive comparison. In addition, due to the design of the reflection cache, a second MemberInfo cache is created for the case-insensitive members, which basically doubles an application's working set.

Use BindingFlags.ExactMatch whenever possible Specify this BindingFlag when calling MethodBase.Invoke if you know that the types of the arguments you are passing exactly match the types of the method's parameters. It will allow reflection to go down an optimized, more efficient code path that does not perform argument type-coercion. If the argument types don't match the method's parameter types, an exception will be thrown.

Call the non-plural GetXX method if you know the name of the instance you care about (.NET Framework 2.0 only) The MemberInfo cache is lazily populated in the .NET Framework 2.0, which means lower working set cost, and less time to retrieve the method. If you know the name of the particular method you want to obtain, use the non-plural GetXX method.

Cache only the handle to a member (.NET Framework 2.0 only) In the .NET Framework 2.0, developers have the ability to define a cache policy themselves. The .NET Framework 2.0 introduces new APIs called the token handle resolution APIs. This set of APIs exposes some of the fundamental member identity concepts of the runtime and allows a user to set up and execute a MemberInfo caching policy on their own.



Reflect性能分析:




posted @ 2013-07-04 09:43  muzizongheng  阅读(346)  评论(0编辑  收藏  举报
如果我们时时忙着展现自己的知识, 将何从忆起成长所需的无知?