Are there any o开发者_高级运维verheads to using the following sytax:
Form1 myForm = new Form1();
myForm.Show();
As opposed to:
Form1 myForm;
myForm = new Form1();
myForm.Show();
When I was learning VB6, I was told doing the quivelent in VB had an overhead - is the same true in .NET?
There is no difference in .Net.
But in VB6 As New
was evil. It had a special meaning: it created an auto-instantiating variable. You could never get a null reference exception with these variables. The VB6 runtime would automatically create a new instance of the object for you.
Dim x As New Foo
x.Bar = 10 ' creates a new Foo '
Set x = Nothing ' destroys the first Foo'
x.Bar = 20 ' NO ERROR - creates a second Foo '
This behaviour was considered evil by most right-thinking programmers: and we avoided As New
like the plague.
But in VB.Net (and C#) there is no difference between Dim x As New Foo
and Dim x As Foo: Set x = New Foo
No. Both are same.
Resulting bytecode when compiling in release mode (and probably debug mode) will be the same.
You have only seperated the declaration from instantiation in the latter case. There's no significant impact of this. I read somewhere that .Net object instantiation takes 0.000007 seconds so it hardly matters though recommended practice would be to instantiate the object only when needed and dispose when not needed or caching not required..
I doubt there is, but even if there was, the performance overhead would be so negligible that there wouldn't be any percievable benefit by choosing one over the other.
In this example you create a variable [myForm] of type Form1 and allocate it memory at creation.
Form1 myForm = new Form1();
In this example the first line creates a variable of type Form1, but no memory has been allocated for this myForm object.
Form1 myForm;
Then the second line can be used whenever you need a new instance of type Form1 [at that point, the memory will be allocated for the myForm object].
myForm = new Form1();
In my opinion, it is really a good pratice to declare all of your variables to there types and then when you need a live instance you can do your ... obj = new Foo1();
精彩评论