我有一个 C# 4.0 应用程序,在这个应用程序中我有很多不必要的变量。就像下面代码中的 _foo
变量:
public string Foo() {
var _foo = "foo bar";
return _foo;
}
正如我所提到的,像这样的情况发生在很多方法中。
大量不必要的变量(如我在本例中解释的变量)会导致 C# 中的性能问题吗?
编辑:
如果我应该删除它们,我不会征求任何建议。我的问题是关于性能效果的。事实上,这个应用程序不是我写的,我是这个项目的新手。我只是看到并想知道它是否有任何性能。除了影响代码质量这一事实之外,还有其他影响。
最佳答案
Would lots of unnecessary variables (like the ones I explained in this case) cause performance problem in C#?
不,他们不会。
当您在 Release 模式下编译并优化您的代码时,编译器足够智能,可以删除所有不必要的东西:
public string Foo()
{
return "foo bar";
}
或更准确地说:
.method public hidebysig instance string Foo() cil managed
{
.maxstack 1
.locals init (
[0] string str)
L_0000: ldstr "foo bar"
L_0005: stloc.0
L_0006: ldloc.0
L_0007: ret
}
与对应的 Debug 模式相比有很大不同:
.method public hidebysig instance string Foo() cil managed
{
.maxstack 1
.locals init (
[0] string _foo,
[1] string CS$1$0000)
L_0000: nop
L_0001: ldstr "foo bar"
L_0006: stloc.0
L_0007: ldloc.0
L_0008: stloc.1
L_0009: br.s L_000b
L_000b: ldloc.1
L_000c: ret
}
从性能的角度来看,这绝对不是您应该担心的事情。您应该担心的是代码的可读性,这个优化的代码示例似乎比您的版本更具可读性。
因此您可以信任不断改进并能够优化此类情况的编译器。
关于c# - 大量不必要的变量会导致 C# 中的性能问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9018602/