省略for语句/ if语句的花括号将导致性能问题

本文关键字:语句 性能 问题 for if 省略 | 更新日期: 2023-09-27 18:12:44

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

性能也取决于变量名吗?

省略for语句/ if语句的花括号将导致性能问题

不,省略花括号不会对性能产生任何影响。您所看到的差异可能是由于开始时的程序预热。交换这两个代码块,您将看到相同的差异或没有差异。

如果您在发布模式下构建程序并在ILSpy (ILSpy version 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();