Which is better?

P

Paul

With respect to performance, is either of these better?

Dim myTextBox As New TextBox

or

Dim myTextBox As TextBox
myTextBox = New TextBox

or

Dim myTextBox As TextBox = New TextBox
 
P

Patrice

It's unlikely you'll ever see a difference (you could even see if it doesn't
create the same underlying MSIL code).

This is the same (unlike VB6 were New was checking for existence at each
access to the variable). 2 may be usefull as it allows to create an object
only when (and in particular *if*) you need it which could could save some
time (under unusual circumstances though it's likely best to avoid creating
something if you don't need it).

As a side note it's likely most often considered better to code for clarity
and to work on identified performance problem rather than to be picky about
few microseconds gains... For example if you use a DB it's likely better to
start by looking at indexes design...


Patrice
 
K

Kevin Spencer

Numbers 1 and 3 are better in terms of performance (not sure if either of
them is better than the other). However, it is minimal.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Neither a follower
nor a lender be.
 
K

Karl Seguin

Hey Kevin,
I'm pretty sure the three are identical:

..method private instance void test() cil managed
{
// Code Size: 21 byte(s)
.maxstack 1
.locals (
[System.Web]System.Web.UI.WebControls.TextBox box1,
[System.Web]System.Web.UI.WebControls.TextBox box2,
[System.Web]System.Web.UI.WebControls.TextBox box3)
L_0000: nop
L_0001: newobj instance void
[System.Web]System.Web.UI.WebControls.TextBox::.ctor()
L_0006: stloc.0
L_0007: newobj instance void
[System.Web]System.Web.UI.WebControls.TextBox::.ctor()
L_000c: stloc.1
L_000d: newobj instance void
[System.Web]System.Web.UI.WebControls.TextBox::.ctor()
L_0012: stloc.2
L_0013: nop
L_0014: ret
}


Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top