"David Sworder" <gilGrissom@CSILasVegas.com> wrote in message
news:uSwckv7JEHA.2012@TK2MSFTNGP11.phx.gbl...[color=blue]
> Hi,
>
> I need to design a method that creates and returns a large array of
> objects. The problem is that the *type* of object to create isn't know
> until
> runtime. As a result, a parameter of type "Type" must be passed in:
>
> IMyInterface[] CreateObjects(Type type,int numberOfObjects);
>
> Internally this method will call Activator.CreateInstance() to create
> the objects. Here's my question: Is there a significant performance
> penalty
> to calling Activator.CreateInstance() versus using "new" to create the
> objects? If so, I'll look for an alternate way to accomplish this task.
>[/color]
It shouldn't be significant, no. While CreateInstance will probably take
longer to execute than the equivilent new calls, it should still be an
insignificant fraction of time, even if you are generating a considerable
number of objects. Run a test and see how long it takes to create the
maximum number of objects you expect. If you are generating *alot* of
objects, then perhaps a factory is more appropriate. Instead of loading x
number of a given object, write a factory class which can create the object,
load the factory with Activator.CreateInstance, and use the factories
CreateObject method to create a new object with whatever parameters you
need. All in all the factory approach may make for cleaner code as well, and
it gives you a bit more flexibility(you could, optionally, pool objects
inside the factory, using IDisposable.Dispose to release the object, change
the concrete type simply by changing the factory code, log creations, etc).
It does require more code for a given object type, and without knowing your
situation I can't say if it would be better or not.
[color=blue]
> I really wish that C# supported generics which would make this type of
> task incredibly easy...
>[/color]
Generics are coming, but the support for generic construction is limited to
parameterless constructors, so its utility is there but less-so than it
would be in many cases.[color=blue]
> --
> Sincerely,
>
> David Sworder
>
http://www.CodeFanatic.com
>
>[/color]