Interesting question. I ran this:
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
through IL DASM and here are the results:
Debug build:
.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
Release build:
.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
You'll note that there are more operations in the debug build but not in the release build.
So to answer your question, it seems that declaring the variable costs a little bit extra in debug builds, which is often the case (optimization not turned on or is not as much optimized). But in the release build (as expected) the optimizer is removes this unecessary operation.