I'm interested in how default variable named the same as the function is implemented.
Sum
always allocated even if I am not using it? (see case 1
)Total
in CASE 3
), is it used instead of Sum
?Are the following 3 equivalent cases also equivalent when compiled? Or is some 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 compiling to less than 32 bytes are inserted inline. I wonder whether in some cases, I might end above or below the limit just because of the chosen notation.
The default return value from a function is int. Unless explicitly specified the default return value by compiler would be integer value from function.
That default return value will always be None . If you don't supply an explicit return statement with an explicit return value, then Python will supply an implicit return statement using None as a return value. In the above example, add_one() adds 1 to x and stores the value in result but it doesn't return result .
Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values.
Python Function without return statement If the function doesn't have any return statement, then it returns None .
I renamed your functions to Sum1, Sum2, and Sum3, respectively and then ran 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 appears that Sum2 and Sum3 result in the same IL. Sum1 appears to be more efficient since it puts the result of the operator directly onto the stack. The others must pull the result off the stack into the local variable and then push it back onto the stack!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With