I've been told to use Reflection.Emit instead of PropertyInfo.GetValue / SetValue because it is faster this way. But I don't really know what stuff from Reflection.Emit and how to use it to substitute GetValue and SetValue. Can anybody help me with this ?
-
2Huh? Reflection.Emit allows you to create code on the fly for later execution. But it's also more complex and error prone, not to mention hard to debug. You need to describe what your are trying to do with GetValue/SetValue, and with what performance requirements. Why are you using Reflection in the first place? – Pontus Gagge Nov 26 '09 at 15:35
-
1I guess he has some dynamically loaded objects and wants to access the property, and the question is about whether calling GetValue/SetValue or *generating IL code to access the property "hard-coded"* would be the better thing. I'd suggest trying with Reflection.Emit.DynamicMethod, and then just checking which one's faster. For me, GetValue/SetValue was sufficient, I just needed to generate IL code for handling events with signatures that are unknown at compile time :) – OregonGhost Nov 26 '09 at 15:42
-
I user reflection to Get and Set Values to Properties of objects (I don't know the type of the objects ) – Omu Nov 26 '09 at 15:58
-
1(re accepted answer: note that this is only faster than reflection if you use HyperDescriptor per the download; it isn't in the BCL) – Marc Gravell Nov 26 '09 at 20:02
5 Answers
Just an alternative answer; if you want the performance, but a similar API - consider HyperDescriptor; this uses Reflection.Emit
underneath (so you don't have to), but exposes itself on the PropertyDescriptor
API, so you can just use:
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj);
props["Name"].SetValue(obj, "Fred");
DateTime dob = (DateTime)props["DateOfBirth"].GetValue(obj);
One line of code to enable it, and it handles all the caching etc.

- 1,026,079
- 266
- 2,566
- 2,900
-
what do you mean by "use HyperDescriptor per the download" ? i just need to get properties, get and set values to them, that's all – Omu Nov 27 '09 at 07:12
-
I mean you need to download the HyperDescriptor component from codeproject and enable it as shown in the page (several different ways). *Without* HyperDescriptor this is jut glorified reflection; HyperDescriptor intercepts TypeDescriptor and replaces the reflection code with dynamic IL. – Marc Gravell Nov 27 '09 at 07:35
-
1It is confusing, I agree; the same code works fine with/without HyperDescriptor, but it is /much/ (~100x) slower without. Any problems getting it working, let me know (it was a few years ago when I wrote it, but I still remember most of it!) – Marc Gravell Nov 27 '09 at 07:37
-
Could you show me how to use it without using the Attributes for classes ? – Omu Dec 14 '09 at 15:26
-
Ok, I found something, I do HyperTypeDescriptionProvider.Add(typeof(Foo)); HyperTypeDescriptionProvider.Add(typeof(Bar)); at the start of the application – Omu Dec 14 '09 at 15:36
-
This is exactly what I've been looking for, however I have a question: Could this somehow be extending to handle fields as well as properties ? AFAIK there's no TypeDescriptor.GetFields method (or similar for that matter) So i'm wondering if you could hook into FieldInfo.SetValue and GetValue instead ? – Steffen Dec 14 '09 at 17:57
-
In principal you could; what level of functionality do you need? Just read or write can be done with `DynamicMethod` or `Expression`. What do you need? Does it have to be a `PropertyDescriptor`, for example? – Marc Gravell Dec 14 '09 at 22:02
-
It's just read and write I need really, currently I use FieldInfo.SetValue and FieldInfo.GetValue (as well as PropertyInfo.SetValue and GetValue, in case there are properties in the reflected class) It doesn't have to a PropertyDescriptor - in fact I'd probably prefer it isn't, as I'm not using PropertyDescriptors at the moment. It's for a DB access lib, which uses reflection for setting the proper fields/properties upon selecting data from the database. Basically a reflected version of this.Id = (int)dr["Id"]; // dr is a DataRow – Steffen Dec 15 '09 at 06:18
-
Just started using this, it's very good. Also, anything with the name Hyper in it is welcome in my projects. – Phil Cooper Dec 17 '12 at 15:09
-
4@Phil to be honest, I tend to use FastMember now: simpler, and supports "dynamic" too – Marc Gravell Dec 17 '12 at 16:55
-
I built something almost identical in function to FastMember. It stems from the necessity to efficiently read generic objects from a data reader. Mine differs in that instead of having a RuntimeTypeAccessor or requiring a string[] of members passed to the constructor, I acquire/cache the member sets dynamically through decorating database class members with [Table] and [Column] attributes. – Triynko Oct 21 '13 at 00:54
-
Also where mine differs, I have not only `ReadEntit(y/ies)
(IDataReader dr, string tableAlias)` methods for reading single entities and lists of single entities, but `List – Triynko Oct 21 '13 at 00:56 -
Have you looked at how FastInvoke compares to HyperDescriptor? FastInvoke seems to output similar IL, but includes things like fast integer opcodes as well. https://code.google.com/p/somemethods/source/browse/trunk/DotNet/Dotnet.Invoke/FastInvoke.cs?r=37 It seems to have also evolved into doing the same thing through using compiled lambda expressions: http://flurfunk.sdx-ag.de/2012/05/c-performance-bei-der-befullungmapping.html – Triynko Oct 21 '13 at 01:23
If you're fetching/setting the same property many times, then using something to build a typesafe method will indeed be faster than reflection. However, I would suggest using Delegate.CreateDelegate
instead of Reflection.Emit. It's easier to get right, and it's still blazingly fast.
I've used this in my Protocol Buffers implementation and it made a huge difference vs PropertyInfo.GetValue/SetValue
. As others have said though, only do this after proving that the simplest way is too slow.
I have a blog post with more details if you decide to go down the CreateDelegate
route.

- 1,421,763
- 867
- 9,128
- 9,194
-
Very interesting - I tried creating a delegate to FieldInfo.SetValue, and it changed absolutely nothing. Fairly obvious really, since all I did was change the way the function is called, and it's the function itself that's slow. So how did you get this performance increase ? I had no luck finding information about it in your blog post (maybe I'm just blind :-D) – Steffen Dec 14 '09 at 18:26
-
Just re-read your blog entry and spotted the GetGetMethod and GetSetMethod part, apparently I *were* blind before. Anyway this obviously explains the speed difference, however for FieldInfos I'm still in the dark :-S I'm however looking forward to Marcs example :-) Just wanted to let you know I found out what you did to speed up things through delegates. – Steffen Dec 14 '09 at 21:19
-
1Cheers (+1) - I just used that idea to save .1s - .8s per page on some reflection populated classes :-) – Keith Feb 02 '10 at 10:56
-
I tried to implement the example in the blog post, using `MagicMethod` for the `SetValue` method, but it is `void` and I get the `The type 'System.Void' may not be used as a type argument.` exception. Did I miss something from your tutorial? – Mentoliptus Oct 18 '12 at 14:02
-
1@Mentoliptus: It's very hard to say without seeing your code. Sounds like you should show a short but complete program in a new question. – Jon Skeet Oct 18 '12 at 14:08
-
@JonSkeet: here is the new question http://stackoverflow.com/questions/12968932/createdelegate-instead-of-reflection-for-setvalue Thank you in advance ;) – Mentoliptus Oct 19 '12 at 06:58
Use PropertyInfo.GetValue/SetValue
If you have performance problems cache the PropertyInfo object (don't repeatedly call GetProperty)
If - and only if - the use of reflection is the performance bottleneck of your app (as seen in a profiler) use Delegate.CreateDelegate
If - and really really only if - you are absolutely sure that reading/writing the values is still the worst bottleneck it's time to start learning about the fun world of generating IL in runtime.
I really doubt it's worth it, each of those levels increase the complexity of the code more then they improve performance - do them only if you have to.
And if runtime access to properties is your performance bottleneck it's probably better going for compile time access (it's hard time to be both generic and super high performance at the same time).

- 29,306
- 10
- 67
- 103
The purpose of Reflection.Emit is completely different from that of PropertyInfo.Get/SetValue. Via Reflection.Emit, you can directly emit IL code, for example into dynamically compiled assemblies, and execute this code. Of course, this code could access your properties.
I seriously doubt that this will be much quicker then using PropertyInfo in the end, and it's not made for this purpose either. You could use Reflection.Emit as the code generator for a small compiler, for example.

- 11,253
- 2
- 33
- 40
Using Reflection.Emit seems a little too "clever", as well as a premature optimization. If you profile your application, and you find that the GetValue/SetValue Reflection is the bottleneck, then you could consider optimizing, but probably not even then...

- 5,054
- 2
- 19
- 17