Considering the following as two versions of a very simple function in Python, the question is which one is preferred over another and why?
Is there any extra memory usage and or CPU usage for case 1 compared to case 2 in which additional assignment has been used?
case 1:
def f(x):
y = x*x
return y
case 2:
def f(x):
return x*x
From my point of view, the case 1 is clearer than the other one especially in case of complex computations and providing many returning objects. On the other hand, the case 2 looks very compact and would be considered as a very attractive so. Since the simple is simply efficient. What do you think?
update:
I didn't know there is disassembler in Python! It was so amazing when I learned the answer of my question and the way to check similar ideas. Special appreciation.
from dis import dis as dasm
dasm(f)
If you want to know what Python style is preferred, look at the code in the standard library:
$ grep return Lib/*py
You will see that the case 2 style is the most common.
I personally use the assignment form only when the variable name is needed to add clarity to the code:
normalized_query = query.replace(' ', '').lower()
return normalized_query
This code introduces a very small bit of overhead for the assignment:
>>> def f(x):
return x + 2
>>> def g(x):
y = x + 2
return y
>>> dis(f)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINARY_ADD
7 RETURN_VALUE
>>> dis(g)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINARY_ADD
7 STORE_FAST 1 (y)
3 10 LOAD_FAST 1 (y)
13 RETURN_VALUE
For the first one:
>>> dis.dis(f)
2 0 LOAD_FAST 0 (x)
3 LOAD_FAST 0 (x)
6 BINARY_MULTIPLY
7 STORE_FAST 1 (y)
3 10 LOAD_FAST 1 (y)
13 RETURN_VALUE
For the second one:
>>> dis.dis(f)
2 0 LOAD_FAST 0 (x)
3 LOAD_FAST 0 (x)
6 BINARY_MULTIPLY
7 RETURN_VALUE
As you can see, there's a (slight) cost in assigning something, even if you're not using it at all except for holding the value before returning.
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