Elegant python and elegant python

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.