比方法调用更快的动作?

时间:2014-04-21 21:25:44

标签: c# .net delegates

前段时间我确实发现了一篇关于Action比纯方法调用更快的文章。我不记得在哪里,但是在那一刻被激活了,做了一些测试,发现它在某些情况下是真的。

今天有人刚才说我测试的是错的,所以,有人能找到原因在这些测试中没有参数的Action比纯方法快吗?我必须说它在x64机器中速度更快,在x86中速度更慢。

class Program
{
    static void Main(string[] args)
    {
        test t = new test();
        t.doTest();
        Console.ReadKey();

    }
}

class test
{
    Stopwatch w;
    int a = 0;

    public void doTest()
    {
        Action doSum = () => { a = a + 1; };
        Action<int> doSumValue = (add) => { a = a + add; };

        w = new Stopwatch();

       Console.WriteLine("-------With params-------");
        for (int round = 0; round < 10; round++)
        {

            a = 0;
            w.Reset();
            w.Start();

            for (int buc = 0; buc < 500000000; buc++)
                sumValue(1);

            w.Stop();
            Console.WriteLine("Function: " + w.ElapsedMilliseconds);

            a = 0;
            w.Reset();
            w.Start();

            for (int buc = 0; buc < 500000000; buc++)
                doSumValue(1);

            w.Stop();
            Console.WriteLine("Action: " + w.ElapsedMilliseconds);



        }

       Console.WriteLine("-------With no params---------");
        for (int round = 0; round < 10; round++)
        {

            a = 0;
            w.Reset();
            w.Start();

            for (int buc = 0; buc < 500000000; buc++)
                sum();

            w.Stop();
            Console.WriteLine("Function: " + w.ElapsedMilliseconds);

            a = 0;
            w.Reset();
            w.Start();

            for (int buc = 0; buc < 500000000; buc++)
                doSum();

            w.Stop();
            Console.WriteLine("Action: " + w.ElapsedMilliseconds);

        }
    }

    void sum()
    {
        a = a + 1;
    }

    void sumValue(int toAdd)
    {
        a = a + toAdd;
    }

}

编辑:将循环次数改为1秒,结果相同

我的机器(i7 2600)上的结果如下:

有大量迭代的新结果

-x86 *使用params

功能:1417ms 行动:1568毫秒

*没有参数

功能:1422ms 行动:1634毫秒

-x64 *使用params

功能:1976ms 行动:2114毫秒

*没有参数

功能:1975ms 行动:1719ms

低迭代次数的旧结果

-x86使用参数

功能:28ms

行动:31毫秒

-x86没有参数

功能:28ms

行动:32毫秒

-x64使用参数

功能:39ms

动作:42毫秒

-x64使用参数

功能:39ms

行动:34毫秒

那么,我的测试是错误的还是操作比调用x64机器中的无参数方法更快?

2 个答案:

答案 0 :(得分:1)

Action是代表。对于.NET中的所有意图和目的,这只是一个方法指针。即它只是一个指向方法的指针,因此逻辑上它执行相同的基本指令并调用一个方法。没有一般的原因,为什么Action比直接调用Action包含的相同方法更快。有很多场景可能会稍微慢一点,因为它是一个方法调用的抽象级别 - 但不是有意义的。

答案 1 :(得分:0)

好吧,Henk Holterman有钥匙,我在发布模式下运行它,但是从visual studio发布它。

手动启动它们,它们的行为速度相同,而不是动作速度更快(而且速度慢很多)。

我很想再次找到那篇文章,我确实找到了这个信息给他发送的结果。

谢谢大家。

相关问题