Vano Maisuradze
Vano Maisuradze

Reputation: 5899

Variable declaration. Optimized way

Which is more optimized way and why?

MyType myType1 = new MyType();
// Do some work with myType1 

myType1 = new MyType();
// Do some work with myType1 

or

MyType myType1 = new MyType();
// Do some work with myType1 

MyType myType2 = new MyType();
// Do some work with myType2

Upvotes: 0

Views: 1046

Answers (6)

Guffa
Guffa

Reputation: 700212

There is no optimisation that you can do that way.

There may be a slight difference, and it's not certain which one would better, as that could change from one system to another. It's mostly depending on what system you are running it on, as it depends on how the JIT compiler optimises the code.

The first option might save some stack space by reusing the variable, but on the other hand it might actually use more stack space. By using the variable in more code, it's less likely that the JIT compiler can optimise it to use a register instead of stack space.

Either way the difference would hardly even be possible to measure, so it's not even worth it to try to optimise the code that way.

You should use the variables so that it's clear what the intention of the code is. There may be a point in using separate variables as they have references to separate objects.

You should not be afraid to use more local variables. As long as you are not doing some recursive stuff so that you risk causing a stack overflow, allocating more local variables doesn't cost anything at all. As the local variables are allocated by simply moving the stack pointer, it literally takes no time at all to make that space larger.

Upvotes: 2

Craig White
Craig White

Reputation: 13992

My simple test thats news to me :) I initialised an object 100,000,000 times and it is apparently faster to create a new one instead of re-using an old one :O

        string output = "";
        {
            DateTime startTime1 = DateTime.Now;
            myclass cls = new myclass();
            for (int i = 0; i < 100000000; i++)
            {
                cls = new myclass();
                cls.var1 = 1;
            }
            TimeSpan span1 = DateTime.Now - startTime1;
            output += span1.ToString();
        }

        {
            DateTime startTime2 = DateTime.Now;
            for (int i = 0; i < 100000000; i++)
            {
                myclass cls = new myclass();
                cls.var1 = 1;
            }
            TimeSpan span2 = DateTime.Now - startTime2;
            output += Environment.NewLine + span2.ToString() ;
        }
        //Span1 took 00:00:02.0391166
        //Span2 took 00:00:01.9331106

public class myclass
{
    public int var1 = 0;
    public myclass()
    {
    }
}

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70314

As a rule of thumb, don't reuse a variable name ever. Create a new one. With a proper name. A name that indicates it is something different from the first variable.

Treat variable names as abundant. Don't worry about computer time. Your time is more precious. You're going to die. Don't worry about reusing variable names. That is just so 1980's!

Upvotes: 1

Davide Piras
Davide Piras

Reputation: 44605

I would always use the second because it's less error prone and even if you copy/paste some parts and then replace the old name with a new one in the second block, you end up with clearer code. in fact only the second block would allow you to access the myType1 var as well down in the method.

anyway this is very generic, consider that if you do a lot of similar things with these objects you could have a method to wrap the common parts and call the method twice.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500055

The second might be very, very slightly slower or take more memory in some cases, as it will have one more stack entry. If this is part of a heavily-recursive method, you'll end up taking up more stack space for the two variables.

Do not use this as a reason to favour the first approach.

You should write the cleanest code you can - if you can write your code so that almost none of your variables change value after declaration, that can make it easier to reason about your code in a functional style.

From a readability point of view, I would usually favour the second approach. It depends on the exact situation though.

Upvotes: 12

Grant Thomas
Grant Thomas

Reputation: 45083

Neither, particularly (omitting consideration for the work done with either.)

The only difference is that you're essentially overwriting an existing reference in the first case. Both variables will be added to the stack in current scope, at the same time (not as required) - but to notice more variables being added to the stack performance-wise isn't so much of a concern with modern machines.

Upvotes: 3

Related Questions