Is the return variable of the function always returned?

I am wondering how the default variable has the same meaning as the function.

  • Does Sum always stand out, even if I don't use it? (see case 1 )
  • If I select another variable ( Total in CASE 3 ), is it used instead of Sum ?

Are the following 3 equivalent cases equivalent when compiling? Or is someone superior to others?

 ' EQUIVALENT CASES ' CASE 1 Function Sum(a As Integer, b As Integer) As Integer Return a + b End Function ' CASE 2 Function Sum(a As Integer, b As Integer) As Integer Sum = a + b End Function ' CASE 3 Function Sum(a As Integer, b As Integer) As Integer Dim Total As Integer Total = a + b Return Total End Function 

As I read somewhere, functions that are less than 32 bytes are inserted into a string. It is interesting whether in some cases it can exceed or below the limit just because of the chosen notation.

+5
source share
2 answers

I renamed your functions to Sum1, Sum2 and Sum3, respectively, and then passed them through LinqPad. Here is the generated IL:

 Sum1: IL_0000: ldarg.1 IL_0001: ldarg.2 IL_0002: add.ovf IL_0003: ret Sum2: IL_0000: ldarg.1 IL_0001: ldarg.2 IL_0002: add.ovf IL_0003: stloc.0 // Sum2 IL_0004: ldloc.0 // Sum2 IL_0005: ret Sum3: IL_0000: ldarg.1 IL_0001: ldarg.2 IL_0002: add.ovf IL_0003: stloc.1 // Total IL_0004: ldloc.1 // Total IL_0005: ret 

It seems that Sum2 and Sum3 lead to the same IL. Sum1 seems more efficient because it pushes the result of the statement directly onto the stack. The rest should pull the result from the stack into a local variable, and then put it back on the stack!

+4
source

I am not a VB.NET expert, but I know something about C #. In C #, this type of code is not valid. You should always return value, otherwise the code will not compile.

I assume VB.NET bypasses this in C #:

 T Sum = default(T); ... return Sum; 

The default value is Sum , which in the case of int is 0 .

In accordance with this logic, the variable gets highlighted for reference types, which means that there will be no allocation, since by default they are null .

Looking at IL:

 .method public static int32 Test() cil managed { // Code size 3 (0x3) .maxstack 1 .locals init ([0] int32 Test) IL_0000: nop IL_0001: ldloc.0 IL_0002: ret } // end of method Module1::Test 

from this Function :

 Function Test() As Integer End Function 

You will see init , which initializes the variable (allocates it) and ldloc , which is a call to get the value of the variable, so it should be highlighted.

+2
source

Source: https://habr.com/ru/post/1211623/


All Articles