Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, Declaring a variable inside for..loop, will it decrease performance? [duplicate]

Tags:

variables

c#

For example:

            for (i = 0; i < 100; i++)
            {
               string myvar = "";
                // Some logic
            }

Do it make performace or memory leak?

Why i do this, because i don't want "myvar" accessible outside the for..loop.

It is any performance monitor, i can compare the execute time between two snippet or whole program ?

thanks you.

like image 735
Cheung Avatar asked Oct 25 '11 02:10

Cheung


2 Answers

No, variables are purely for the programmer's convenience. It doesn't matter where you declare them. See my answer to this duplicate question for more details.

like image 184
StriplingWarrior Avatar answered Oct 11 '22 00:10

StriplingWarrior


Perhaps you could check out an old test that I once did regarding another conversation. Variable declaration. Optimized way

The results turned out that it was faster to redefine but not as easy on memory.

My simple test. I initialised an object 100,000,000 times and it is was 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()
    {
    }
}
like image 42
Craig White Avatar answered Oct 11 '22 01:10

Craig White