省略for-statement / if-statement的花括号会导致性能问题?

时间:2014-07-14 14:33:33

标签: c# c#-4.0

Stopwatch t1 = new Stopwatch();

t1.Start();
int i = 0;
for (int j = 0; j < 2000000001; j++)
     i += 1;
t1.Stop();



Stopwatch t2 = new Stopwatch();

t2.Start();
int k = 0;
for (int j = 0; j < 2000000001; j++)
{
     k += 1;
}
t2.Stop();

Console.WriteLine(t1.Elapsed);
Console.WriteLine(t2.Elapsed);

Console.ReadLine();

O / P:

00:00:05.0266990

00:00:04.7179756

性能还取决于变量名吗?

1 个答案:

答案 0 :(得分:7)

不,省略花括号对性能没有任何影响。你看到的差异可能是由于程序在一开始就变暖了。交换这两个代码块,你会看到相同的差异或没有。

如果您在发布模式下构建程序并在ILSpy (ILSpy版本2.1.0.1603)中打开可执行文件,那么您将看到已添加花括号。 :

private static void Main(string[] args)
{
    Stopwatch t = new Stopwatch();
    t.Start();
    int i = 0;
    for (int j = 0; j < 2000000001; j++)
    {
        i++;
    }
    t.Stop();
    Stopwatch t2 = new Stopwatch();
    t2.Start();
    int k = 0;
    for (int l = 0; l < 2000000001; l++)
    {
        k++;
    }
    t2.Stop();
    Console.WriteLine(t.Elapsed);
    Console.WriteLine(t2.Elapsed);
    Console.ReadLine();
}

原始代码:

Stopwatch t1 = new Stopwatch();
t1.Start();
int i = 0;
for (int j = 0; j < 2000000001; j++)
    i += 1;
t1.Stop();
Stopwatch t2 = new Stopwatch();

t2.Start();
int k = 0;
for (int j = 0; j < 2000000001; j++)
{
    k += 1;
}
t2.Stop();