views:

33

answers:

3

I would like to know how will performance go when I instantiate multiple classes in one form.

e.g

    Public Class frmClass

      Dim obja As New ClassA
      Dim objb As New ClassB
      Dim objc As New ClassC

      'I'll use those classes' attribute in here
      '

   End Class

Thanks for your help!

+2  A: 

Well, it will depend on how expensive those classes are. If their constructors decide to download the whole of wikipedia, it will be expensive... but generally speaking, it shouldn't be a problem.

Create instances of the classes you need, and no others - you should be fine. Creating objects is generally pretty cheap in .NET. I would suggest that for the sake of clarity, you only create an object when you need to though, rather than creating everything and then using all the objects later.

You should also consider whether you really want these to be instance variables or not - are they all logically part of the state of your form? Would it make more sense for some of them to be local variables? A class which has a vast amount of state probably wants refactoring. This is more for the sake of getting clean code than performance though.

Jon Skeet
Thanks a lot Tony the Pony!
RedsDevils
+1  A: 

Object creation is generally very cheap, and even the most basic Form is actually going to have a whole heap of other dependent things being loaded. So frankly: go for it.

Unless your objects are actually massive / have some enormous connection/etc cost - in which case maybe consider lazy loading. But generally (and especially for managed code) this isn't going to be an issue.

There are some things where you might want to wait for OnLoad, purely because you need the hWnd - but these are more rare.

Marc Gravell
Thanks too Marc!
RedsDevils
A: 

This really depends on how these classes are designed and what actions they perform when the constructor is invoked. If they have default empty constructors then the performance hit of instantiating three new objects won't be noticeable.

Darin Dimitrov