在最近在编程时遇到这个问题之后,我一直在想这个问题。以下是2个合法且可编译的代码段。具体来说,我的问题是..在第二种情况下,括号会使程序变慢吗?还有为什么允许这样做?
第一种情况:
if (statement)
{
// do something
}
第二种情况:
{
if (statement)
{
// do something
}
}
此外,如果我有类似下面的代码该怎么办。运行时与调用函数X相同,没有任何花括号。
{
{
{
// call function X
}
}
}
最佳答案
在大多数情况下,它没有任何区别-您绝对应该为提高可读性编写代码,而不是其他任何事情。
但是,花括号可能会以令人惊讶的方式影响性能,尽管这很不寻常。考虑以下代码:
using System;
using System.Collections.Generic;
class Test
{
static void FewerCurlies()
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 100; i++)
{
int x;
if (i % 3 == 0)
{
actions.Add(() => x = 10);
}
int y;
if (i % 3 == 1)
{
actions.Add(() => y = 10);
}
}
}
static void MoreCurlies()
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 100; i++)
{
{
int x;
if (i % 3 == 0)
{
actions.Add(() => x = 10);
}
}
{
int y;
if (i % 3 == 1)
{
actions.Add(() => y = 10);
}
}
}
}
}
MoreCurlies
中的多余花括号看起来是多余的,对吗?不太...生成的代码看起来像这样:using System;
using System.Collections.Generic;
class Test
{
static void FewerCurlies()
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 100; i++)
{
FewerCurliesCapture capture = new FewerCurliesCapture();
if (i % 3 == 0)
{
actions.Add(capture.Method1);
}
if (i % 3 == 1)
{
actions.Add(capture.Method2);
}
}
}
static void MoreCurlies()
{
List<Action> actions = new List<Action>();
for (int i = 0; i < 100; i++)
{
{
MoreCurliesCapture1 capture = new MoreCurliesCapture1();
if (i % 3 == 0)
{
actions.Add(capture.Method);
}
}
{
MoreCurliesCapture1 capture = new MoreCurliesCapture2();
if (i % 3 == 1)
{
actions.Add(capture.Method);
}
}
}
}
private class FewerCurliesCapture
{
public int x;
public int y;
public void Method1()
{
x = 10;
}
public void Method2()
{
y = 10;
}
}
private class MoreCurliesCapture1
{
public int x;
public void Method()
{
x = 10;
}
}
private class MoreCurliesCapture2
{
public int y;
public void Method()
{
y = 10;
}
}
}
这里的区别是:
FewerCurlies
的循环的每次迭代中创建捕获类的实例。FewerCurlies
中使用的每个捕获类实例都包含两个变量,即使每个委托(delegate)实际上仅使用其中一个变量,而在MoreCurlies
中,每个捕获类仅捕获单个变量所有这些都是特定于实现的,但是它表明看起来多余的curlies可能会产生影响。