(original) (raw)
food for thought as noticed by a coworker who has been profiling some hot code to optimize a library...
If a function does not have a return statement we return None.� Ironically this makes the foo2 function below faster than the bar2 function at least as measured using bytecode size:
Python 2.6.2 (r262:71600, Jul 24 2009, 17:29:21)
[GCC 4.2.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> def foo(x):
...�� y = x()
...�� return y
...
>>> def foo2(x):
...�� return x()
...
>>> def bar(x):
...�� y = x()
...
>>> def bar2(x):
...�� x()
...
>>> dis.dis(foo)
� 2���������� 0 LOAD_FAST��������������� 0 (x)
������������� 3 CALL_FUNCTION����������� 0
������������� 6 STORE_FAST�������������� 1 (y)
� 3���������� 9 LOAD_FAST��������������� 1 (y)
������������ 12 RETURN_VALUE�������
>>> dis.dis(foo2)
� 2���������� 0 LOAD_FAST��������������� 0 (x)
������������� 3 CALL_FUNCTION����������� 0
������������� 6 RETURN_VALUE�������
>>> dis.dis(bar)
� 2���������� 0 LOAD_FAST��������������� 0 (x)
������������� 3 CALL_FUNCTION����������� 0
������������� 6 STORE_FAST�������������� 1 (y)
������������� 9 LOAD_CONST�������������� 0 (None)
������������ 12 RETURN_VALUE�������
>>> dis.dis(bar2)
� 2���������� 0 LOAD_FAST��������������� 0 (x)
������������� 3 CALL_FUNCTION����������� 0
������������� 6 POP_TOP������������
������������� 7 LOAD_CONST�������������� 0 (None)
������������ 10 RETURN_VALUE�������