New in many ways Python performance optimizations see the value of swapping two variables can be used
A, B = b,a
This can improve performance
>>> from Timeit import timer>>> Timer ("t=a;a=b;b=t", "a=1;b=2"). Timeit () 0.06279781319366587> >> Timer ("A,b=b,a", "a=1;b=2"). Timeit () 0.0378979925538232>>>
From the running time, it really saved half the time.
Get Python bytecode with dis
>>> def func (): ... b = b,a...>>> Import dis>>> Dis.dis (func) 2 0 load_fast 0 (b) 3 load_fast 1 (a) 6 rot_two 7 store_fast 1 (a) store_fast 0 (b) load_const 0 (None) RETURN _value>>>
It can be seen that the main rot_two instruction is the credit:
Consult a Python document for instructions such as Rot_two Rot_three Rot_four, which can be exchanged directly for two variables, three variables, and four variable values
Read the ceval.c file in the source code of python3.4 to see:
TARGET (rot_two) { Pyobject *top = Top (); Pyobject *second = second (); Set_top (second); Set_second (top); Fast_dispatch (); } TARGET (rot_three) { Pyobject *top = Top (); Pyobject *second = second (); Pyobject *third = third (); Set_top (second); Set_second (third); Set_third (top); Fast_dispatch (); }
Is that the specific C language of these instructions implements the
After all, the speed is fast or because A, B = B,a is all using the pointer operation
Python Variable Exchange performance optimization