Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Object Instances Faster Than Reflection in Windows CE

So after looking at an article describing how to Create Object Instances Faster Than Reflection I got really excited since in my code I currently have quite a bit of reflection. Unfortunately DynamicMethod and ILGenerator are not supported in Windows CE. EDIT: Activator is supported in Windows CE

I was wondering if anyone knew of any way to create object instances faster than reflection in CE. If not, maybe someone could explain why Windows CE does not support this feature and if there are any work arounds to get this feature in CE. Even if I had to code my own DynamicMethod and ILGenerator classes it might be worth it :)

like image 663
Ian Dallas Avatar asked Feb 28 '11 21:02

Ian Dallas


2 Answers

First, Activator is supported. Take a look at the docs here.

That said, it's not the fastest thing on the planet, especially if you intend to create more than one instance of the given type. What I did in the OpenNETCF.IoC framework after lots of testing of different way to build up the object was to cache the ConstructorInfo on a per-type basis (specifically in the ObjectFactory class) and used that for object creation. Yes, you've got to use reflection to get the CI the first time, but subsequent calls are very fast since you've already got the delegate.

like image 176
ctacke Avatar answered Sep 28 '22 03:09

ctacke


Depending on your design, you might be able to create a set of (compile-time) instantiating delegates (you can store in a static class).

For example:

static class Factory<T> {
    public Func<T> Creator { get; set; }
}

var instance = Factory<TSomething>.Creator();

//Elsewhere
Factory<SomeClass>.Creator = () => new SomeClass();

This will only help if you can populate the factory in advance with the relevant types.


If all you have is a Type (as opposed to a generic parameter), you can store delegates in a Dictionary<Type, Func<object>>, although it will be less efficient due to casting.
You'd still need to populate the dictionary.

like image 45
SLaks Avatar answered Sep 28 '22 02:09

SLaks