直接返回值或创建临时变量之间的性能差异
与直接返回分配给该变量的值相比,在函数中创建一个临时变量是否有性能下降或内存消耗方面的差异?
Is there any performance hit or memory consumption difference to creating a temporary variable in a function compared to returning directly the value assigned to this variable?
例如,以下哪个函数(GetValue)的性能更好并且可以节省内存,或者两者完全相同:
For example, which of these functions (GetValue) are better in performance and for saving memory or both are exactly the same:
情况1:
private string GetValue()
{
return this.GetResult();
}
private string GetResult()
{
// Code here that return a big string...
}
情况2:
private string GetValue()
{
string result = this.GetResult();
return result;
}
private string GetResult()
{
// Code here that return a big string...
}
谢谢.
在这些基本情况下,可读性总是胜过性能差异.我认为这充其量是微优化,这在很大程度上浪费了时间.不确定的GC运行会耗尽您节省下来的钱.
In these basic situations, readability always trumps performance differences. I'd consider this a micro-optimisation at best, and these largely turn out to be wastes of time. What you save on this will be eaten up by an undeterministic GC run.
在大多数情况下,如果允许编译器对其进行优化,则结果代码中不会有差异.在这种情况下,生成的IL似乎还有一些额外的操作码来引用堆栈上的字符串,但是JIT对此所做的工作却是所有人的猜测.
Most of the time there are no differences in the resulting code if the compiler is allowed to optimise it. The resulting IL in this case seems to have a few extra op codes for a reference to the string on the stack, but what the JIT then does with this is anyone's guess.
有时我会分成一些临时变量以在返回之前对其进行检查,但是我从不担心会对性能产生影响.最重要的是,我从未见过需要进行此类改进才能解决性能问题的情况.
I sometimes break out into temporary variables to review them before returning, but I never worry about the performance impact. Most importantly, I have never seen a case where this sort of improvement was required to solve a performance problem.