Bar*_*art 1 c# performance local-variables compiler-optimization
使用额外的局部变量存储方法的结果时是否存在性能损失?
public string void ToFunkyDutchDate(DateTime this theDate) {
var result = string.Format("{0:dd-MM-yyyy}", theDate);
return result;
}
Run Code Online (Sandbox Code Playgroud)
在类似的琐碎案例中,我甚至可以立即返回格式化的字符串.但这只是一个简单的例子,因为在一些更复杂的函数中,我经常使用这个"技巧"将结果首先分配给临时局部变量.
我的主要原因是这样可以更轻松地进行调试.我可以在线上放一个断点return result;,运行并检查我的函数出现的结果是否正确.
但额外的临时result变量仍然感觉有点像无法使用的替代品而没有:"
public static string ToFunkyDutchDate(DateTime this theDate) {
return string.Format("{0:dd-MM-yyyy}", theDate);
}
Run Code Online (Sandbox Code Playgroud)
我用三种方式缓解了这种唠叨的感觉:
result会使代码更容易理解return very long multi-line expression,这会使性能下降更糟糕/optimize+)时.但是我已经这么做了很多年了,在如此多的代码行中,我想我最后会问它.这里的任何编译器向导都知道吗?:)
编辑:一分钟内回答一个已经酝酿多年的问题.Stackoverflow有多棒.伟大的工具:http://tryroslyn.azurewebsites.net/
xan*_*tos 10
通常没有速度差异.例如,参见http://goo.gl/b9856y和 http://goo.gl/WfIhmT
这两个版本的代码在发布模式下生成相同的IL代码.
在调试模式下,IL代码会更长一些(因为对本地变量的存储是明确的):http://goo.gl/KCkORV