C#哪个更快/同时或为?

时间:2009-11-24 04:08:50

标签: c# refactoring c#-2.0 benchmarking

我有一个C#.NET 2.0脚本,我想知道为什么下面的代码会比同类的while循环更快。

private double getStop(double avgPrice, bool longTrading)
    {
        double stopS = 0.0;
        double stopL = 0.0;

        for (int i = 0; i < 13; i++)
        {
            if (i == 0 || i == 12)
            {
                stopS = 0.0;
                stopL = 0.0;
            }
            else
            {
                if ((lines[i] - ((lines[i] - lines[i - 1]) / 2)) < avgPrice && avgPrice < (lines[i + 1] - ((lines[i + 1] - lines[i]) / 2)))
                {
                    if (avgPrice < lines[i])
                    {
                        stopL = (lines[i] - ((lines[i] - lines[i - 1]) / 2));
                        stopS = lines[i];
                    } else {
                        stopL = lines[i];
                        stopS = (lines[i + 1] - ((lines[i + 1] - lines[i]) / 2));
                    }
                }
            }
        }

        if (longTrading)
        {
            return stopL;   
        } else {
            return stopS;   
        }   
    }

另外,只是明确声明每个if语句而不是在for循环中执行它们会更快吗?

由于回答如此之快,为什么这会比上面的代码慢得多?

private double getStop(double avgPrice, bool longTrading)
    {
        double stopS = 0.0;
        double stopL = 0.0;

        for (int i = 0; i < 13; i++)
        {
            if (i == 0 || i == 12)
            {
                stopS = 0.0;
                stopL = 0.0;
                skip = true;
            }

            if (!skip && (lines[i] - ((lines[i] - lines[i - 1]) / 2)) < avgPrice && avgPrice < (lines[i + 1] - ((lines[i + 1] - lines[i]) / 2)))
                {
                    if (avgPrice < lines[i])
                    {
                        stopL = (lines[i] - ((lines[i] - lines[i - 1]) / 2));
                        stopS = lines[i];
                    } else {
                        stopL = lines[i];
                        stopS = (lines[i + 1] - ((lines[i + 1] - lines[i]) / 2));
                    }
                }
            }
           skip = false;
        }

        if (longTrading)
        {
            return stopL;   
        } else {
            return stopS;   
        }   
    }

3 个答案:

答案 0 :(得分:4)

性能差异应该可以忽略不计,但for循环更清晰,所以我会选择。

答案 1 :(得分:3)

它们应该基本相同。您的'for'循环被评估为:

int i = 0;
while (i < 13)
{
   //all other stuff
   i++;
}; 

答案 2 :(得分:2)

循环变化并没有太大的不同,它取决于上下文和编程语言。

但我的意见是,for语句不会执行,直到constaint(s)匹配,因此 应该比/同时