Ian Frawley wrote:
I have used the Activator class a number of times in my Windows apps and
Windows Services and was thinking of using it again in one of my web
services that I have been developing. I have been told that this is a bad
idea as it will greatly affect the performance of my web service. So I
have been thinking about it and all my other apps use the Activator class
to instantiate objects that hang around for the uptime of the app on start
up, whereas my web service will be using it to create and object each time
it needs one. This makes me think (obviously) that, this is where the
performance hit will take place.
So my question is: I will still be instantiating an object each time I
need one directly so will the activator class add much of an overhead to
this anyway?
The problem is simply that object instantiation with Reflection (which is
what Activator does) is much slower than direct instantiation of the same
object. In .NET 2, many things related to Reflection have been sped up
enormously, but I haven't explicitely tested the Activator to see if it's
one of the classes that work much faster now. But still, there's a great
overhead involved when creating objects dynamically.
Obviously, while this problem doesn't have anything to do with the type of
app you're writing, it'll be more pronounced the more objects you create
with this mechanism. You should probably think about two things: (1) are
you sure you really need to create all these objects dynamically? Wouldn't
there be a way around that? and (2) Could you cache and reuse objects that
you created once instead of creating them every time you need them?
Finally, the general warning: Don't just believe someone who says, "this
or that will be very slow." Things like these always depend on your exact
application, so you should make up your own mind based on some tests you
should do, as close to the final app as possible. Calculate the number of
objects you are going to create, simulate the complexity of the objects in
question, create a small test program and try it out!
Oliver Sturm
--
Expert programming and consulting services available
See
http://www.sturmnet.org (try /blog as well)