Thursday, October 12, 2006 - Posts

When to Declare Variables?

Any performance Guru's out there that can answer the following (cause frankly I don't know).

I was looking at some code and wondered what the impact was.  Here are the two options

Option 1:
     protected void Page_Load(object sender, EventArgs e)
    {
        string id = Request.QueryString["ID"];
       
        if (id == null || id.Length == 0)
            return;
       
        Response.Write(id);

       /* Declare after any conditional logic, saves clock cycles and memory???? */
       MyBusinessObject mbo1 = new MyBusinessObject();
       MyBusinessObject mbo2 = new MyBusinessObject();
       MyBusinessObject mbo3 = new MyBusinessObject();
       MyBusinessObject mbo4 = new MyBusinessObject();
       MyBusinessObject mbo5 = new MyBusinessObject();

       
        mbo1.Write();
        mbo2.Write();
        mbo3.Write();
        mbo4.Write();
        mbo5.Write();
    }

Option 2:
     protected void Page_Load(object sender, EventArgs e)
    {
       /* Variables declared at the top of the method before an conditional logic */
       MyBusinessObject mbo1 = new MyBusinessObject();
       MyBusinessObject mbo2 = new MyBusinessObject();
       MyBusinessObject mbo3 = new MyBusinessObject();
       MyBusinessObject mbo4 = new MyBusinessObject();
       MyBusinessObject mbo5 = new MyBusinessObject();
      
        string id = Request.QueryString["ID"];
       
        if (id == null || id.Length == 0)
            return;
       
        Response.Write(id);

        mbo1.Write();
        mbo2.Write();
        mbo3.Write();
        mbo4.Write();
        mbo5.Write();

       
    }


The differences here are subtle.  I'm wondering if the differences though are valid and justifiable.  In the first example, all of the business objects are declared AFTER some conditional checking.  In the second example, the business objects are declared at the top of the file. 

My take (I don't know how correct I am):

Performance wise, #2 could be slightly worse seeing as how memory would be allocated for the business objects and any static constructors as well as constructor logic would run however little, only to throw them away shortly.  Is that negligle?  Always?  If not, where's the crossover point?

Readability wise I like #2.  It reminds me of Pascal, where all variables are up at the top.  No hunting to find variable declarations.

Your thoughts?  Any MSIL, memory, or performance gurus care to take a stab?
with 2 Comments