VB.Net:通过使用函数本身来保存返回值而不是声明局部变量,是否可以获得某些东西?

d7s*_*rai 2 vb.net

什么是最佳实践(在VB.Net中):

Function GetSomething() as String
    GetSomething = "Here's your string"
End Function
Run Code Online (Sandbox Code Playgroud)

要么

Function GetSomething() as String
    Dim returnString as String = "Here's your string"
    Return returnString
End Function
Run Code Online (Sandbox Code Playgroud)

显然,这些实现都没有任何意义,但它们只是为了说明我的观点.有没有什么可以通过使用GetSomething自己来存储返回值而不是在returnString本地声明然后返回它(它是否避免分配/实例化额外的字符串 - 如果是这样,是否有任何性能/内存优势)?

ste*_*nar 7

有趣的问题.我跑了这个:

Function GetSomething1() As String
    GetSomething1 = "Here's your string"
End Function

Function GetSomething2() As String
    Dim returnString As String = "Here's your string"
    Return returnString
End Function
Run Code Online (Sandbox Code Playgroud)

通过IL DASM,结果如下:

调试版本:

.method public instance string  GetSomething1() cil managed
{
  // Code size       9 (0x9)
  .maxstack  1
  .locals init ([0] string GetSomething1)
  IL_0000:  nop
  IL_0001:  ldstr      "Here's your string"
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  ret
} // end of method Form1::GetSomething1

.method public instance string  GetSomething2() cil managed
{
  // Code size       13 (0xd)
  .maxstack  1
  .locals init ([0] string GetSomething2,
           [1] string returnString)
  IL_0000:  nop
  IL_0001:  ldstr      "Here's your string"
  IL_0006:  stloc.1
  IL_0007:  ldloc.1
  IL_0008:  stloc.0
  IL_0009:  br.s       IL_000b
  IL_000b:  ldloc.0
  IL_000c:  ret
} // end of method Form1::GetSomething2
Run Code Online (Sandbox Code Playgroud)

发布版本:

.method public instance string  GetSomething1() cil managed
{
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string GetSomething1)
  IL_0000:  ldstr      "Here's your string"
  IL_0005:  stloc.0
  IL_0006:  ldloc.0
  IL_0007:  ret
} // end of method Form1::GetSomething1

.method public instance string  GetSomething2() cil managed
{
  // Code size       8 (0x8)
  .maxstack  1
  .locals init ([0] string GetSomething2,
           [1] string returnString)
  IL_0000:  ldstr      "Here's your string"
  IL_0005:  stloc.1
  IL_0006:  ldloc.1
  IL_0007:  ret
} // end of method Form1::GetSomething2
Run Code Online (Sandbox Code Playgroud)

您会注意到调试版本中有更多操作,但发布版本中没有.

所以为了回答你的问题,似乎在调试版本中声明变量的成本有点多,这通常就是这种情况(优化没有打开或没有那么多优化).但是在发布版本中(正如预期的那样),优化器会删除这种不必要的操作.