Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improving performance reflection - what alternatives should I consider?

Tags:

I need to dynamically set values on a bunch or properties on an object, call it a transmission object.

There will be a fair number of these transmission objects that will be created and have its properties set in a short space of time. I want to avoid the use of reflection.

Are there alternatives? If so are there sample implementations I could look at?

like image 881
AndyMM Avatar asked Jun 22 '09 15:06

AndyMM


People also ask

Are there any alternatives that can be used to the annual performance review that may be more beneficial to the employees?

Here are four alternatives to the traditional annual performance appraisal: Feedback, Focus, and Future Chat—During a Feedback, Focus, and Future Chat, you take a more informal approach to the performance appraisal conversation. There is no rating scale and no formal review forms to fill out.

Why is it important to reflect on your own work performance?

Reflecting helps you to develop your skills and review their effectiveness, rather than just carry on doing things as you have always done them. It is about questioning, in a positive way, what you do and why you do it and then deciding whether there is a better, or more efficient, way of doing it in the future.


2 Answers

Use Delegate.CreateDelegate to turn a MethodInfo into a strongly-typed delegate. This can improve performance massively. I have a blog post about this with sample code. Note that this is only going to help if you need to set the same properties multiple times - basically it means that a lot of the type checking is done once when you create the delegate, rather than on every invocation.

Marc Gravell has a HyperPropertyDescriptor project which achieves even better performance, but introduces an extra dependency. This project became the jumping off point for the more modern Fast Member (github). In general you would use Fast Member over HyperProperty.

like image 63
Jon Skeet Avatar answered Sep 17 '22 13:09

Jon Skeet


In .NET 4.0 (beta), you can do this with the updated expression trees, using Expression.Block and Expression.Assign - then compile that to a typed delegate; job done.

In .NET 2.0 and above (as Jon mentioned) HyperDescriptor is a reasonable option - it works as a custom PropertyDescriptor implementation, so you just do code like:

// store this collection for optimum performance
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(
    typeof(SomeType));
props["Name"].SetValue(obj, newName);
props["DateOfBirth"].SetValue(obj, newDoB);

This still has a little boxing, but that isn't actually a bottleneck.

like image 32
Marc Gravell Avatar answered Sep 20 '22 13:09

Marc Gravell