Elegant python and elegant python
Dis-Disassembler for Python bytecode, that is, decompiling python code into bytecode instructions.
Easy to use:Python-m dis xxx. py
I am confused when I see that while 1 is faster than while True on the Internet. Why is this difference?
So we used dis for in-depth analysis.
Suppose the code of est_while.py is as follows.
#coding=utf-8while 1: passwhile True: pass
The following section uses dis for analysis.
E:\>python -m dis test_while.py 2 0 SETUP_LOOP 3 (to 6) 3 >> 3 JUMP_ABSOLUTE 3 5 >> 6 SETUP_LOOP 10 (to 19) >> 9 LOAD_NAME 0 (True) 12 POP_JUMP_IF_FALSE 18
According to the official python documentation, the output report format of dis is as follows.
The output is divided in the following columns:
The parameter interpretation recognizes local and global variable names, constant values, branch targets, and compare operators.
As you can see, in while 1 (line 1), The JUMP_ABSOLUTE command is directly used;
While True here (5th rows), composed of LOAD_NAME and POP_JUMP_IF_FALSE commands.
Originally, True is not a keyword in python2, but a built-in variable, bool type. The value is 1, that is, True + True outputs 2.
It can also be assigned a value. For example, you can assign a value of True = 2 or even True = False.
Therefore, when the value is while True, the value of True must be checked for each loop, corresponding to the command LOAD_NAME.
This is why while True is slower than while 1.
However, in python3, True becomes the keyword. The while 1 and while True commands are the same, so there is no performance difference.