In our game (mobile-oriented), we have several different types of entities, and I write factory / repository to process instances of new objects. Each particular type of object has its own factory implementation, and these plants are managed by EntityRepository.
I would like to implement a repository as such:
Repository { private Dictionary <System.Type, IEntityFactory<IEntity>> factoryDict; public T CreateEntity<T> (params) where T : IEntity { return factoryDict[typeof(T)].CreateEntity() as T; } }
Usage example
var enemy = repo.CreateEntity<Enemy>();
but I'm worried about performance, especially related to the typeof (T) operation in the above. I understand that the compiler will not be able to determine the type of T, and it will need to be determined at run time through reflection, is this correct? One of the options:
Repository { private Dictionary <System.Type, IEntityFactory> factoryDict; public IEntity CreateEntity (System.Type type, params) { return factoryDict[type].CreateEntity(); } }
to be used as
var enemy = (Enemy)repo.CreateEntity(typeof(Enemy), params);
in this case, when typeof () is called, the type is at hand and can be determined by the compiler (right?), and performance should be better. Will there be a noticeable difference? any other considerations? I know that I can also have a method like CreateEnemy in the repository (we have only a few types of entities) that would be faster, but I would prefer to keep the repository as small as possible than the entity.
EDIT:
I know that this is most likely not to be a bottleneck, my only concern is that it is such a waste of time to use time for reflection when there is a slightly less dry alternative. And I think this is an interesting question :)
I did some benchmarking that turned out to be quite interesting (and which seem to confirm my initial suspicions).
Using the performance measurement tool that I found at http://blogs.msdn.com/b/vancem/archive/2006/09/21/765648.aspx (which runs the test method several times and displays metrics like average time and etc.). I did a basic test, testing:
private static T GenFunc<T>() where T : class { return dict[typeof(T)] as T; }
vs
private static Object ParamFunc(System.Type type) { var d = dict[type]; return d; }
called
str = GenFunc<string>();
vs
str = (String)ParamFunc(typeof(String));
respectively. Paramfunc shows a remarkable performance improvement (GenFunc takes an average of 60-70% of the time), but the test is quite rudimentary, and I can skip a few things. In particular, how casting is performed in a common function.
The interesting thing is that there is a small (negligible) performance obtained by "caching" a type in a variable and passing it to ParamFunc vs using typeof () every time.