Reputation: 21545
Given 2 similar python functions:
def get_text(filename):
with open(filename, 'rb') as f:
text = pickle.load(f)
return text
and
def get_text2(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
Would there be any performance difference betwen get_text
and get_text2
? Or will the python interpreter still have to do an assignment under the covers before returning?
This question is mostly about the assignment to a local variable before return -- the unpickling a file part is just a convenient example I had handy.
Upvotes: 3
Views: 174
Reputation: 21545
Thanks to @jonrsharpe for mentioning that I could dis
this which I think provides the answer:
This done with python 3.7.1
>>> def get_text(filename):
... with open(filename, 'rb') as f:
... text = pickle.load(f)
... return text
...
>>> def get_text2(filename):
... with open(filename, 'rb') as f:
... return pickle.load(f)
...
>>> import dis
>>> dis.dis(get_text)
2 0 LOAD_GLOBAL 0 (open)
2 LOAD_FAST 0 (filename)
4 LOAD_CONST 1 ('rb')
6 CALL_FUNCTION 2
8 SETUP_WITH 16 (to 26)
10 STORE_FAST 1 (f)
3 12 LOAD_GLOBAL 1 (pickle)
14 LOAD_METHOD 2 (load)
16 LOAD_FAST 1 (f)
18 CALL_METHOD 1
20 STORE_FAST 2 (text)
22 POP_BLOCK
24 LOAD_CONST 0 (None)
>> 26 WITH_CLEANUP_START
28 WITH_CLEANUP_FINISH
30 END_FINALLY
4 32 LOAD_FAST 2 (text)
34 RETURN_VALUE
>>> dis.dis(get_text2)
2 0 LOAD_GLOBAL 0 (open)
2 LOAD_FAST 0 (filename)
4 LOAD_CONST 1 ('rb')
6 CALL_FUNCTION 2
8 SETUP_WITH 12 (to 22)
10 STORE_FAST 1 (f)
3 12 LOAD_GLOBAL 1 (pickle)
14 LOAD_METHOD 2 (load)
16 LOAD_FAST 1 (f)
18 CALL_METHOD 1
20 RETURN_VALUE
>> 22 WITH_CLEANUP_START
24 WITH_CLEANUP_FINISH
26 END_FINALLY
28 LOAD_CONST 0 (None)
30 RETURN_VALUE
The get_text2
version which returns right away avoids the STORE_FAST
, POP_BLOCK
and LOAD_FAST
instructions -- but I agree the cost is probably negligible.
I think in many cases returning right away results in shorter cleaner code as well.
Upvotes: 3