在多线程情况下,为什么静态变量要比局部变量慢?

时间:2019-07-15 07:56:55

标签: c# .net multithreading local-variables static-variables

我需要使用两个线程来执行两种递增和递减方法。但是,请不要在这里考虑线程同步的问题。

在我的计算机上,我运行以下代码的DoProcessing(),它将为Incrment()和Decrement()创建两个线程。这两个线程将通过访问共享共享的静态变量,计数器来计数循环。此方法完成后,需要 13,865 ms

class MyCounting
{
    public static int maxLoop = int.MaxValue / 2;
    public static long counter;

    public void DoProcessing()
    {
        counter = 0;
        Thread thread1 = new Thread(x =>
        {
            Increment();
        });
        Thread thread2 = new Thread(x =>
        {
            Decrement();
        });

        thread1.Start(); thread2.Start();

        thread1.Join();
        thread2.Join();
        Console.WriteLine($"count is {counter}");
    }
    public void Decrement()
    {
        for (int i = 0; i < maxLoop; i++)
        {
            counter --;
        }
    }

    public void Increment()
    {
        for (int i = 0; i < maxLoop; i++)
        {
            counter++;
        }
    }
}

但是当我不使用静态变量counter来记录循环,而在每种方法上使用局部变量localCounter来记录循环时间。

循环完成后,将localCounter添加到静态变量counter中。

我运行以下代码的DoProcessing(),此方法完成后,只需要 2,730 ms

class MyCounting
{
    public static int maxLoop = int.MaxValue / 2;
    public static long counter;

    public void DoProcessing()
    {
        counter = 0;
        Thread thread1 = new Thread(x =>
        {
            Increment();
        });
        Thread thread2 = new Thread(x =>
        {
            Decrement();
        });

        thread1.Start(); thread2.Start();

        thread1.Join();
        thread2.Join();
        Console.WriteLine($"count is {counter}");
    }
    public void Decrement()
    {
        long localCounter = 0;
        for (int i = 0; i < maxLoop; i++)
        {
            localCounter--;
        }
        counter += localCounter;
    }

    public void Increment()
    {
        long localCounter = 0;
        for (int i = 0; i < maxLoop; i++)
        {
            localCounter++;
        }
        counter += localCounter;
    }
}

在两个测试代码中,我不使用线程同步。我不知道两个测试代码之间的区别,这将导致使用静态变量的执行性能不佳。

您如何解释在使用静态变量时会导致性能下降。

0 个答案:

没有答案
相关问题