Static string versus non-static string

I am a programmer, and therefore I always try to optimize my code. Recently, I played with loops, and I came across something that confused me a bit. I created a simple console application and created a non-static class:

public class CL
{
    static int X;
    string Z;
    static string sZ;

    public CL(int x, int y, string z)
    {
        X = x + 1;
        Z = z;
        sZ = z;
    }

    public void Update(int i)
    {
        X *= i + 1;
        X = X / 2;
        Z += i.ToString() ;
    }

    public void UpdateStatic(int i)
    {
        X *= i + 1;
        X = X / 2;
        sZ += i.ToString();
    }
}

There are two methods that perform the same operations: they both modify a static integer X, and then add an integer ito the string, which is either static ( sZin UpdateStatic) or not ( Zin Update).

I started the loop and here are the results: enter image description here

, 260 , ( fps). X , , . : ?, ? :

    static void Main(string[] args)
    {
        while (Console.ReadLine() != "Q")
        {
            int count = 20000;
            List<CL> l = new List<CL>();
            List<CL> sl = new List<CL>();
            for (int i = 0; i < count; i++)
            {
                var cl = new CL(i, i * 2, "");
                l.Add(cl);
                sl.Add(cl);
            }
            Stopwatch s = new Stopwatch();
            s.Start();
            for (int i = 0; i < count; i++)
            {
                l[i].Update(i);
            }
            s.Stop();
            Console.WriteLine(s.Elapsed + " unsorted list modifying non-static variable");
            s.Reset();

            s.Start();
            for (int i = 0; i < count; i++)
            {
                sl[i].UpdateStatic(i);
            }
            s.Stop();
            Console.WriteLine(s.Elapsed + " unsorted list modifying static variable");
            s.Reset();
        }

    }

, . , . .

+4
1

CL . Z .

sZ .

, , .

, - . , , .net. (4 )

+9

Source: https://habr.com/ru/post/1526267/


All Articles